如何在Django的模板中获取模型的对象数? [英] How can I get the object count for a model in Django's templates?

查看:77
本文介绍了如何在Django的模板中获取模型的对象数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是我的Django应用程序,我正在获取特定模型的所有对象,如下所示:

I'm my Django application I'm fetching all the objects for a particular model like so:

secs = Sections.objects.filter(order__gt = 5)

我将这个varbiles传递给我的模板,我可以访问所有模型的属性如 section.name section.id 等。

I pass this varbiles to my templates and i can access all the properties of the Model like section.name, section.id, etc.

有一个名为 Books 的模型,它有一个FK到 Sections 模型。当我在我的模板中迭代 secs varible时,如何访问每个部分的图书计数?像 {{sec.Books.count}} ??

There is a model called Books which has a FK to the Sections model. When i iterate over the secs varible in my template, how can i access the count of Books for each Section? Something like {{ sec.Books.count }}??

谢谢

推荐答案

如果书籍有一个ForeignKey到部分,那么Django将自动创建从Sections返回到Books的反向关系,这将被称为 books_set 。这是一个经理,这意味着你可以使用 .filter() .get() .count(),您可以在模板中使用这些。

If Books has a ForeignKey to Sections, then Django will automatically create a reverse relationship from Sections back to Books, which will be called books_set. This is a Manager, which means you can use .filter(), .get() and .count() on it - and you can use these in your template.

{{ sec.books_set.count }}

(顺便说一句,你应该为你的模型使用单数名词名字,而不是复数 - 而不是书籍。该模型的一个实例保存一本书的信息,而不是很多。 )

(By the way, you should use singular nouns for your model names, not plurals - Book instead of Books. An instance of that model holds information for one book, not many.)

这篇关于如何在Django的模板中获取模型的对象数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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