Reputation: 564
Let's say I have a column named item_type which contains values such as jeans, trousers, t-shirts etc.
How can I group the count of values of this column and find the maximum value out of the groups?
I am running the below query get the groupings
Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('item_type')
where Item is my model name.
However, this returns the grouped lists as a dictionary of lists, but I need the maximum count out of these groupings.
This is what is returned through my HTML template:
{'item_type': 'jeans', 'total': 250}
{'item_type': 'shirts', 'total': 350}
{'item_type': 'track-pants', 'total': 502}
{'item_type': 'trousers', 'total': 136}
{'item_type': 'tshirts', 'total': 450}
How do I retrieve just this: {'item_type': 'track-pants', 'total': 502}
Further, is there a way to extract the max values as variables? Basically I want the value of the key item_type which is track-pants and the same for total which is 502 in this case.
Upvotes: 0
Views: 55
Reputation: 5482
You can use the annotated total in order_by statement. You can order by count and get the first item, like this:
Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('-total')[0]
Upvotes: 1