Search code examples
pythondjangodjango-querysetdjango-databasedjango-aggregation

How to count all ForeignKey models with exact field values in Django?


I'm not sure if it's possible or not, but I want to count all votes associated with a model with an exact vote_type attribute.

Here's the model:

class Link(models.Model):
    title       = models.CharField(max_length=200)
    . . . 

class Vote(models.Model):
    UP, DOWN = range(2)
    TYPE_CHOICES = [(UP, "Upvote"), (DOWN, "DownVote")]

    link = models.ForeignKey(Link, related_name='votes')
    vote_type = models.IntegerField(choices=TYPE_CHOICES, db_index=True)
    . . . 

I used this to count all votes:

Link.objects.annotate(ups=Count('votes')).order_by('-ups')

and thought maybe I could use this to achieve what I want:

Link.objects.annotate(ups=Count('votes__vote_type__exact=1')).order_by('-ups')

But it seems I can not use filter() syntax here.

I'm using Django 1.8.4.


Solution

  • You can just filter the votes based on type before you perform the annotation.

    Link.objects.filter(votes__vote_type=1).annotate(ups=Count('votes')).order_by('-ups')
    

    Source: https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses