[Fixed]-Django count a field but group by another

1👍

You actually already wrote the answer in your question. As far as I know, COUNT in SQL excludes certain falsey values like NULL. So if you want to count the falsey values as well, you use another field to perform the aggregate, just like you did in your SQL statement where you used the ‘id’ field. On that note, all you need to do is to perform COUNT on ‘id’. Change your code to something like this:

results = MyModel.objects.all()\
    .values('region')\
    .annotate(total=Count('id'))

Leave a comment