1👍
To do what you’re trying to achieve in one query, you need to use Count
, annotate
and values_list
I’ll show you a code example and then I’ll try to explain it:
from django.db.models import Count
from your_project.models import *
Genre.objects.all().values_list('name').annotate(num_books=Count('book'))
.values_list('name')
: This return a list of all genres by name.annotate(num_books=Count('book'))
: This count books for eachGenre
I have a similar models structure in my projects and when I execute that code, I get this as answer:
[(u'GENRE_NAME', 13), (u'GENRE_NAME', 14), (u'GENRE_NAME', 0),...]
You can parse the output of this query to fit your expectations
I also recomend you to check oficial documentation Django Agreggation
0👍
This loops over all your genres and prints out how many of them there are.
Even if there are 0 in a genre.
for a_genre in Gendre.objects.all():
print Book.objects.filter(genre=a_genre).count()
and if you want it printed with the genre aswel
for a_genre in Gendre.objects.all():
print "%s (%d)" % (a_genre, Book.objects.filter(genre=a_genre).count())
Documentation for filters in django : https://docs.djangoproject.com/en/1.7/topics/db/queries/#retrieving-specific-objects-with-filters
- [Answer]-Use HttpResponse with JSON data in this code
- [Answer]-Django Templates: How does it decide where to load a template?
Source:stackexchange.com