Tejas Gaykar
Tejas Gaykar

Reputation: 91

how to sort by count in django queryset?

I tried using this query but not giving expected result.

ships = Shipment.objects.filter(added_on__gte=("2016-10-22")).annotate(sku_count=Count('sku')).order_by('sku_count')

Upvotes: 3

Views: 3048

Answers (2)

matias elgart
matias elgart

Reputation: 1181

you said in your comment above that you wanted the object. you should be able to do this:

ships = Shipment.objects.filter(added_on__gte("2016-10-22")).annotate(sku_‌​count=Count('sku')).‌​order_by('sku_count'‌​)

the only thing is that you will have duplicate rows for the same sku. remember that when you use 'group by', you're aggregating multiple values (Shipment instances) by a value common to them (sku).

so like Vikram said above, you can get unique skus and their count like this:

Shipment.objects.filter(added_on__gte("2016-10-22")).values(‌​"sku").annotate(sku_‌​count=Count('sku')).‌​order_by('sku_count'‌​)

but in order to get specific Shipment instances, you'll have to fetch Shipment instances by 'sku' at that point. HTH.

Upvotes: 3

Vikram Singh Chandel
Vikram Singh Chandel

Reputation: 1308

If you want to group by with 'sku' column and sort by its count, this can help you.

# Ascending order
ships = Shipment.objects.filter(added_on__gte=("2016-10-22")).values("sku").annotate(sku_count=Count('sku')).order_by('sku_count')

# Descending order
ships = Shipment.objects.filter(added_on__gte=("2016-10-22")).values("sku").annotate(sku_count=Count('sku')).order_by('-sku_count')

Upvotes: 4

Related Questions