Django难以显示数据(计数) [英] Django difficulty in displaying the data(count)

查看:138
本文介绍了Django难以显示数据(计数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的模型

 
name = models.CharField(max_length = 128)
created = models.DateTimeField('创建日期')


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()
vote = models.IntegerField(default = 0)


def __str __(self):
return self.book_title

我的查询数据库在django shell

  Subject.objects.all()
>>> [<主题:电子><主题:compter science>]

q = Subject.objects.get(id = 2)
q.book_set.all()
>> ; [< Book:python django>< Book:python flask>]

我应该如何获得每个科目的书籍数量。 (获得图书数量 电子科学和计算机科学科目)我知道这可以是直截了当的答案。我想在论坛中显示模板,其中显示主题名称和包含的图书数量



有人可以帮我查询以获取图书数量每个科目



任何帮助都非常感谢。提前谢谢

解决方案

如果您只需要某个主题的图书数量,则 计数

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

如果您需要计数对于他们的书籍数量,您可以 注释

 从django.db.models导入计数
主题=主题.objects.annotate(num_books = Count('book'))

主题中的subj:
print sub j.num_books


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

解决方案

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 

这篇关于Django难以显示数据(计数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆