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

后端 未结 3 1013
陌清茗
陌清茗 2020-12-24 01:16

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

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

I pa

3条回答
  •  没有蜡笔的小新
    2020-12-24 01:31

    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:

    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.

提交回复
热议问题