Note that there are some explanatory texts on larger screens.

plurals
  1. POFiltering Django Query by the Record with the Maximum Column Value
    primarykey
    data
    text
    <p>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 <a href="https://stackoverflow.com/questions/586781/postgresql-fetch-the-row-which-has-the-max-value-for-a-column">these</a> <a href="https://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column/123511#123511">questions</a>, but in the specific context of Django's ORM.</p> <p>e.g.</p> <p>Say I have a model designed to store the historical values of everyone's phone numbers.</p> <pre><code>class Person(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) </code></pre> <p>with the records:</p> <pre><code>Person(name='Jim',phone='123-456-9870', created=datetime(2005,1,2,4,2)) Person(name='Jim',phone='329-802-9870', created=datetime(2006,9,2,7,8)) Person(name='Sue',phone='324-345-3450', created=datetime(2008,7,4,6,1)) </code></pre> <p>Now say I wanted to find everyone's most recent phone number.</p> <p>In SQL, I'd usually have to use a subquery to calculate the maximum values:</p> <pre><code>SELECT p1.name, p1.phone, p1.created FROM person_person p1, ( SELECT name, MAX(created) AS max_created FROM person_person GROUP BY name ) AS p2 WHERE p1.name = p2.name AND p1.created = p2.max_created </code></pre> <p>Is there any mechanism in Django that could simplify this?</p> <p>I'm using PostgreSQL on my backend, so any thoughts or solutions that would rely on PostgreSQL specific functionality would be helpful.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload