Opened 10 years ago

Closed 10 years ago

#16760 closed New feature (wontfix)

ORM: Manager.latest() use pk by default

Reported by: freek.wiekmeijer@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


This is a proposal for a small improvement in the ORM layer.

The Manager class I'm referring to is django.db.models.manager.Manager. It has a public method named latest() which retrieves the most recent record from the applicable database table. For example MyModel.objects.latest() returns a MyModel object.

Current behaviour:
You need to specify which database column to use for the latest() method. Either through a Meta class in the model ("get_latest_by" option), or as a parameter in the latest() call (i.e. MyModel.objects.latest('id')).

Suggested change:
In many situations you just want the object with the highest primary key value, which is typically the latest record inserted into the table.
Change latest() to use the models primary key by default, if no "get_latest_by" is specified in the model and no parameter is supplied to the method call.

Change History (2)

comment:1 Changed 10 years ago by Travis Swicegood

Triage Stage: UnreviewedDesign decision needed

comment:2 Changed 10 years ago by Jacob

Resolution: wontfix
Status: newclosed

I understand the use case here, but latest is specifically designed for dates, not for primary keys. Remember: we can't guarantee that the PK is in order, or even a number. Think, for example, about a model that uses UUIDs for primary keys.

Thanks for the idea!

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