Django Query to get count of all distinct values for particular column [duplicate]
Asked Answered
D

1

6

I am trying to fetch count of all distinct values in particular column for example I have following table in model name MyModel :

Id  City     vendor

1   Mumbai      2
2   Pune        3
3   Mumbai      1
4   Yavatmal    2
5   Pune        5

I am looking for output something like this:

[{'Mumbai':2},{'Pune':2},{'Yavatmal':1}]
Distributive answered 30/4, 2016 at 10:17 Comment(0)
G
18

Like the comment of solarissmoke above. In that post you can see the solution:

from django.db.models import Count
MyModel.objects.values('city').annotate(the_count=Count('city'))
Gilles answered 30/4, 2016 at 13:24 Comment(1)
This doesn't actually work properly, you need to also use order_by, as done answer in the duplicate. Without it the count is just equal to 1 for everything.Adama

© 2022 - 2024 — McMap. All rights reserved.