57

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 pass this varbiles to my templates and i can access all the properties of the Model like section.name, section.id, etc.

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

Thank you

5 Answers 5

93

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.)

Sign up to request clarification or add additional context in comments.

Comments

17

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.

Comments

7

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

1 Comment

{{ section.books|length }} does not work for me
0

For Django 3.0, If the Book model is related to Section model,

{{ sec.books_set.all.count }}

The working is already mentioned in the answer by @Daniel Roseman

Comments

0
menus = Menu.objects.filter(parent__name__isnull=True)

{% for menu in menus %}

{% if menu.childs.count > 0 %}
...

{% endif %}

1 Comment

Your suggestion would be even more helpful if you used the model names and variables from the question. It's not clear this really answers the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.