[Answer]-Django, get an object from a list of filtered objects which has the maximum value for a field

1👍

At this point, you have two choice:

First, use “max” to get the max value of certain field and use that max value to retrieve the particular student instance.
Good side, this is easy to implement; bad side, you need to hit database twice to achieve your goal.

Second, use raw(). You can perform all the complicate query you want. And that will solve your problem.
Good side, you have the maximal freedom to preform any query; bad side, require sql knowledges.

0👍

‘objs=Modelname.objects.filter(student__in=malerep).order_by(‘-Votes’,’-student__Percentage’)’
then using objs[0] i was able to access the object of the student with max votes and max percentage in case of a tie.

Leave a comment