Opened 8 years ago
Closed 7 years ago
#27953 closed Cleanup/optimization (fixed)
Make default Model.__str__() more useful (such as by displaying the primary key)
Reported by: | Victor Porton | Owned by: | kapil garg |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.10 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
In [4]: t Out[4]: <Transaction: Transaction object>
For objects with a PK, it should display instead the value of PK, like this:
Out[4]: <Transaction: pk=7>
If the model has no PK, display like this:
Out[4]: <Transaction: no pk>
Change History (7)
comment:1 by , 8 years ago
comment:2 by , 8 years ago
Yes, I agree it would be nice to do *something* about this problem.
In your example, <Transaction: Transaction object>
is the repr
of the object, and the Transaction object
part is the str
of the object.
Demo:
>>> class Foo(models.Model): ... class Meta: ... app_label = 'admin' ... >>> Foo() <Foo: Foo object> >>> str(Foo()) 'Foo object' >>> repr(Foo()) '<Foo: Foo object>'
So we must think about how __repr__
and __str__
will behave. Having Model.__str__
return pk=...
regardless of the model type sounds suboptimal.
comment:3 by , 8 years ago
Summary: | Models should display IDs → Make default Model.__str__() more useful (such as by displaying the primary key) |
---|---|
Triage Stage: | Unreviewed → Someday/Maybe |
Type: | New feature → Cleanup/optimization |
Here's a past django-developers discussion on the topic. An interested person could revive that thread to try to get a consensus.
comment:4 by , 8 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
Triage Stage: | Someday/Maybe → Accepted |
comment:5 by , 8 years ago
https://github.com/django/django/pull/8336
(1) is my first choice, pk=1 is my second choice. I'd be fine with either.
I know that this can be done manually with every model, but I want to do it automatically for all models, to reduce code repeating and do it always.