Skip to content
Advertisement

Filtering Django Query by the Record with the Maximum Column Value

Is there an easy way to filter a Django query based on which record has a max/min value in a column? I’m essentially asking these questions, but in the specific context of Django’s ORM.

e.g.

Say I have a model designed to store the historical values of everyone’s phone numbers.

with the records:

Now say I wanted to find everyone’s most recent phone number.

In SQL, I’d usually have to use a subquery to calculate the maximum values:

Is there any mechanism in Django that could simplify this?

I’m using PostgreSQL on my backend, so any thoughts or solutions that would rely on PostgreSQL specific functionality would be helpful.

Advertisement

Answer

You’ll probably just want to use raw SQL here, the raw() manager method facilitates this, allowing you to return model instances from your query. The only trick is that the raw query needs to include the primary key. This should probably work for you (unless you have the primary key set to something other than id):

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement