Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 260
Mridang Agarwalla Avatar asked Aug 03 '10 11:08

Mridang Agarwalla


People also ask

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {{ NAME }} this mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does Django template contains?

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

What {% include %} does in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.


2 Answers

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

like image 183
Daniel Roseman Avatar answered Sep 28 '22 12:09

Daniel Roseman


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.

like image 23
Mbuso Avatar answered Sep 28 '22 12:09

Mbuso