user3449833 user3449833 - 1 year ago 83
Python Question

Django Count of Items in a Field

class Event(models.Model):
name = models.CharField(max_length=20, unique=True)
distance = models.IntegerField()
date = models.DateField()

class Category(models.Model):
name = models.CharField(max_length=20, unique=True)
description = models.CharField(max_length=20, unique=True)
isnew = models.BooleanField(default=False)

class Result(models.Model):
event = models.ForeignKey(Event)
category = models.ForeignKey(Category)
score = models.IntegerField()

I want to do a query to return a count of each unique Category in the Result table, for a given Event.

What I'm doing now is something like:

results = Result.objects.filter(event=myevent)
categorycountdict = {}
for r in results:
if r.category in categorycountdict:
categorycountdict[r.category] += 1
categorycountdict[r.category] = 1

Is there a better way, perhaps by query instead of python.

Answer Source

You can use annotate() with values(). This approach is shown in the docs for values(). To get the count for each category name, you could do:

from django.db.models import Count

categories = Result.objects.filter(

This will return a list of dictionaries with keys category__name and count, for example:

[{'count': 3, 'category__name': u'category1'}, {'count': 1, 'category__name': u'category2'}]

You could convert this to a single dictionary by using a dictionary comprehension:

counts_by_category = {d['category__name']: d['count'] for f in categories}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download