ORM: Manager.latest() use pk by default
|Reported by:||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.3|
|Cc:||Triage Stage:||Design decision needed|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||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.
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')).
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.