Skip to content Skip to sidebar Skip to footer

Django Difficulty In Displaying The Data(count)

Im new to django and trying to learn with building a forum my model class Subject(models.Model): name=models.CharField(max_length=128) created=models.DateTimeField('Created

Solution 1:

If you only need the number of books for a certain subject, there is count

Subject.objects.get(id=2).book_set.count()

If you need the subjects with a count for the number of books for them you can annotate

from django.db.models import Count
subjects = Subject.objects.annotate(num_books=Count('book'))

for subj in subjects:
    print subj.num_books 

Post a Comment for "Django Difficulty In Displaying The Data(count)"