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 Victor Porton, 8 years ago

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.

comment:2 by Aymeric Augustin, 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 Tim Graham, 8 years ago

Summary: Models should display IDsMake default Model.__str__() more useful (such as by displaying the primary key)
Triage Stage: UnreviewedSomeday/Maybe
Type: New featureCleanup/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 kapil garg, 8 years ago

Owner: changed from nobody to kapil garg
Status: newassigned
Triage Stage: Someday/MaybeAccepted

comment:5 by Collin Anderson, 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.

comment:6 by Tim Graham <timograham@…>, 7 years ago

In 7c9cb1ed:

Refs #27953 -- Removed hardcoded uses of Model.str() in tests.

comment:7 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: assignedclosed

In 1a49b89:

Fixed #27953 -- Added instance's pk to Model.str().

Note: See TracTickets for help on using tickets.
Back to Top