Django Count of Items in a Field
<p>models.py</p>

<pre><code>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()
</code></pre>

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

<p>What I'm doing now is something like:</p>

<pre><code>results = Result.objects.filter(event=myevent)
categorycountdict = {}
for r in results:
    if r.category in categorycountdict:
        categorycountdict[r.category] += 1
    else:
        categorycountdict[r.category] = 1
</code></pre>

<p>Is there a better way, perhaps by query instead of python.</p>

<p>You can use <code>annotate()</code> with <code>values()</code>. This approach is shown in the docs for <a href="https://docs.djangoproject.com/en/1.10/topics/db/aggregation/#values" rel="nofollow"><code>values()</code></a>. To get the count for each category name, you could do:</p>

<pre><code>from django.db.models import Count

categories = Result.objects.filter(
    event=myevent,
).order_by('category').values(
    'category__name'
).annotate(count=Count('category__name'))
</code></pre>

<p>This will return a list of dictionaries with keys <code>category__name</code> and <code>count</code>, for example:</p>

<pre><code>[{'count': 3, 'category__name': u'category1'}, {'count': 1, 'category__name': u'category2'}]
</code></pre>

<p>You could convert this to a single dictionary by using a dictionary comprehension:</p>

<pre><code>counts_by_category = {d['category__name']: d['count'] for f in categories}
</code></pre>

python django django-models