retrieve row with maximum field value django

5,610 views
Skip to first unread message

Nkansah Rexford

unread,
Jul 23, 2015, 9:58:14 PM7/23/15
to Django users
Say I have a model

class MyModel(models.Model)
    name = models.CharField(max_length=20)
    age = models.IntergerField()

How can I find the maximum based on the 'Age' field number and retrieve that whole object? I understand aggregates allows me to find and retrieve the maximum number when given a field to run on, but I only get the maximum number ONLY and not the other items in the row.

Does django have something that allows to find the maximum (or minimum) value of a database field, then retrieve whole row in the query?

James Schneider

unread,
Jul 24, 2015, 12:11:18 AM7/24/15
to django...@googlegroups.com

Use a combination of order_by('-age') and first() on your query set.

MyModel.objects.order_by('-age').first()

https://docs.djangoproject.com/en/1.8/ref/models/querysets/#order-by

Obviously that only pulls the "first" object even if multiple objects have that same age, so you may need additional filter() and sorting criteria.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5fc15560-93f6-4ba2-a30f-287f1fe76713%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nkansah Rexford

unread,
Jul 24, 2015, 6:49:18 AM7/24/15
to Django users, jrschn...@gmail.com
Thank you. This will do for my needs for now.  Picking the first max value that comes at the top is fine for me.
Reply all
Reply to author
Forward
0 new messages