Python 如何在 Django 的模板中获取模型的对象计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3395863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:50:03  来源:igfitidea点击:

How can I get the object count for a model in Django's templates?

pythondjangodjango-models

提问by Mridang Agarwalla

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

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

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

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

我通过这个varbiles到我的模板,我可以访问该模型的所有属性,如section.namesection.id等。

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

有一个称为模型的模型Books,该Sections模型具有该模型的 FK 。当我遍历secs模板中的变量时,如何访问每个部分的书籍数量?之类的{{ sec.Books.count }}??

Thank you

谢谢

采纳答案by Daniel Roseman

If Bookshas 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.

如果Books有一个 ForeignKey to Sections,那么 Django 会自动创建一个从 Sections 回到 Books 的反向关系,这将被称为books_set。这是一个管理者,你可以使用的手段.filter().get().count()在其上-你可以在你的模板中使用这些。

{{ sec.books_set.count }}

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

(顺便说一句,您应该为模型名称使用单数名词,而不是复数 -Book而不是Books。该模型的一个实例包含一本书的信息,而不是很多。)

回答by Mbuso

Additionally to what Daniel said, Django creates reverse relationships automatically (as Daniel said above) unless you override their names with the related_name argument. In your particular case, you would have something like:

除了 Daniel 所说的之外,Django 会自动创建反向关系(如 Daniel 上面所说),除非您使用 related_name 参数覆盖它们的名称。在您的特定情况下,您会有类似的东西:

class Book(models.Model):
    section = models.ForeignKey(Section, related_name="books")

Then you can access the section's books count in the template by:

然后,您可以通过以下方式访问模板中该部分的图书计数:

{{ sec.books.count }}

As you intimated in your question.

正如您在问题中所暗示的那样。

回答by Ramy M. Mousa

As for a 2019answer. I would suggest making use of related_namewhile making your ForeignKeyto look like that:

至于2019年的答案。我建议related_name在使您ForeignKey看起来像这样的同时使用:

section = models.ForeignKey(Section, on_delete=models.SET_NULL, related_name='books')

Then you can use it as follows:

然后您可以按如下方式使用它:

{{ section.books.count }} 

or

或者

{{ section.books|length }}