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