[Django]-Django + postgres and select distinct

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

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

Leave a comment