Django difficulty in displaying the data(count)

拟墨画扇 提交于 2019-12-12 02:45:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!