Friday, July 24, 2015

Re: retrieve row with maximum field value django

Thank you. This will do for my needs for now.  Picking the first max value that comes at the top is fine for me.


On Friday, July 24, 2015 at 4:11:18 AM UTC, James Schneider wrote:

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

On Jul 23, 2015 6:58 PM, "Nkansah Rexford" <seanm...@gmail.com> wrote:
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?

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/df23eac2-0fa3-43d7-a709-99c7e41ecc71%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment