5๐
The distinct argument has to match the first order argument. Try using this:
BookingCatalog.objects.filter(...) \
.order_by('boat', '-rank', 'is_skippered') \
.distinct('boat')
๐คNS0
1๐
The way that I do this is to select the distinct objects first, then use those results to filter another queryset.
# Initial filtering
result = BookingCatalog.objects.filter(...)
# Make the results distinct
result = result.order_by('boat').distinct('boat')
# Extract the pks from the result
result_pks = result.values_list("pk", flat=True)
# Use those result pks to create a new queryset
restult_2 = BookingCatalog.objects.filter(pk__in=result_pks)
# Order that queryset
result_2 = result_2.order_by('-rank', 'is_skippered')
print(result_2)
I believe that this results in a single query being executed, which contains a subquery. I would love for someone who knows more about Django to confirm this though.
๐คkbuilds
- [Django]-Django โ Ordering by a foreign key
- [Django]-Set language of template in Django by clicking on <a> link from Bootstrap Dropdown menu
- [Django]-Django 'User' object has no attribute 'user'
- [Django]-How can I include user profile's images/logos on django comments
0๐
..ordering by -rank will give you the lowest rank of each duplicate, but your overall query results will be ordered by boat field
BookingCatalog.objects.filter (...).order_by('boat','-rank','is_skippered').distinct('boat')
For more info on, refer to Django documentation
including for Postgres
๐คuser4426017
- [Django]-A correct case to use Django signals
- [Django]-Bad gateway on django+gunicorn+nginx configuration
- [Django]-Using `defer` or `only` on ForeignKey
Source:stackexchange.com