Filter out objects in django

Question:

I’m new to Django and not very familiar with SQL either.
I have a Django model that describes a person and has all sorts of fields, two of them are

  1. country
  2. race_time

I want to be able to filter out all of the objects and leave only the fastest persons with the best race_time, 1 person per 1 country.

How can I do that with Django filtering?

Asked By: Itai Bar

||

Answers:

The best approach as Hemal said is the following:

YourObject.objects.order_by('country', 'race_time').distinct('country')

The reason for this syntax is that:

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For more details you can check out this docs.

Answered By: haduki
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.