Counting objects within a Foreign Key and ManyToMany in Django
I'd like to count the objects I have listed.
I would like to count the number of issues within each title.
This is how my models.py are setup:
# Edited out
Views.py:
def titles (request):
all_titles = Title.objects.all().o开发者_Python百科rder_by('title')
num_titles = Title.objects.all().count()
latest_titles = Title.objects.order_by('-date_added')
title_a = Title.objects.filter(title__startswith='A')
title_b = Title.objects.filter(title__startswith='B')
......etc......
I need to do this for creators and characters too, except they are in a Many to Many relationship with Issue and the views essentially look the same as the def titles
Thank you.
To get the related issues for each title you can use the backwards relationship lookup. Since you did not specify a related name in the Issue model where you created the relationship, the lookup is performed using _set
appended to the lower cased name of the related model. In your case issue_set
.
some_title = Title.object.get(pk=1)
some_title.issue_set.count()
However, this is going to perform a db hit for every title you want to count.
You probably want to annotate the titles qs with the count. docs
from django.db.models import Count
titles_with_counts = Title.objects.all().annotate(issue_count=Count('issue__id'))
now each title in that qs has count accessible by using .issue_count
for title in titles_with_counts:
print title.title, title.issue_count
精彩评论