[Fixed]-Django count on many-to-many

20👍

Since you want the number of articles that have each keyword, you have to do it the other way:

>>> Keyword.objects.all().annotate(article_count=models.Count('article'))[0].article_count
2

9👍

This is the same as the answer from Vebjorn Ljosa, but with a little context, where article_set is the related_name of the reverse many-to-many relationship object.

keywords_with_article_counts = Keyword.objects.all().annotate(article_count=Count('article_set'))

To illustrate your results, it would be easier to return the .values():

keywords_with_article_counts.values('keyword', 'article_count')

Which would return a list of dictionaries that would look something like this:

[{'article_count': 36, 'keyword': u'bacon'}, 
 {'article_count': 4, 'keyword': u'unicorns'}, 
 {'article_count': 8, 'keyword': u'python'}]

1👍

i don’t know how you would do it efficiently but if you need to get it done.

keywords = Keyword.objects.all()
for keyword in keywords:
  print 'Total Articles: %d' % (Article.objects.filter(keywords=keyword).count())

Leave a comment