Code

Opened 3 years ago

Closed 3 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

Description

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

Context:
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.

Attachments (0)

Change History (2)

comment:1 Changed 3 years ago by tswicegood

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design decision needed

comment:2 Changed 3 years ago by jacob

  • Resolution set to wontfix
  • Status changed from new to closed

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!

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.