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'}]
- Multiple form classes in django generic (class) views
- Django: instance needs to have a primary key value before a many-to-many relationship
- Django template counter in nested loops
- How to serve static files to AWS when deploying Django app (`python manage.py collectstatic` didn't work)?
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())
- Django-autocomplete-light simple usage
- RuntimeError: Never call result.get() within a task Celery
- Session authentication with Django channels
- Django form dropdown list of stored models
Source:stackexchange.com