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

后端 未结 3 1010
陌清茗
陌清茗 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:35

    As for a 2019 answer. I would suggest making use of related_name while making your ForeignKey to look like that:

    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 }}
    

提交回复
热议问题