views:

1335

answers:

1

I have a list of objects how can I run a query to give the max value of a field:

I'm using this code:

def get_best_argument(self):
        try:
            arg = self.argument_set.order_by('-rating')[0].details
        except IndexError:
            return 'no posts'
        return arg

rating is an integer

+5  A: 

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." statement
Argument.objects.all().aggregate(Max('rating'))

If you've already gotten the list out of the database, then you'd do something like this:

from django.db.models import Max
args = Argument.objects.all()
# Calculates the maximum out of the already-retrieved objects
args.aggregate(Max('rating'))

This is untested so I may have made a mistake somewhere, but there you go.

musicfreak
typo: "import Avg" --> "import Max"?
Tom
yea I made that change in my code
Johnd
I need the actuall argument object that has that Max, so I can print the details field. The args.aggregate(Max('rating')) call just returns the highest rating. I'm looking for the arg with the highest rating.
Johnd
@Johnd: Oh, I see. My mistake. I don't know how to do that off the top of my head, I'll let you know if I find a way.
musicfreak
What's wrong with your exiting code - Argument.objects.order_by("-rating")[0]?
AdamKG
adam, I was just wondering if there is a better way
Johnd