问题
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 Date')
def __str__(self):
return self.name
class Book(models.Model):
book_subject=models.ForeignKey(Subject,on_delete=models.CASCADE)
book_title=models.CharField(max_length=128)
url=models.URLField()
votes=models.IntegerField(default=0)
def __str__(self):
return self.book_title
my query to database in django shell
Subject.objects.all()
>>>[<Subject: electronics>, <Subject: compter science>]
q=Subject.objects.get(id=2)
q.book_set.all()
>>>[<Book: python django>, <Book: python flask>]
How should i get the number of books for each subjects. (to get count of books for electronics and computer science subjects) I know this could be straight forward answer. I wanted to show the template as in forum where it displays subject name and number of books it contains
Can someone help me with query to get number of books for each subjects
Any help is much appreciated..Thanks in advance
回答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
来源:https://stackoverflow.com/questions/35357279/django-difficulty-in-displaying-the-datacount