90π
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.)
16π
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.
- [Django]-Database returned an invalid value in QuerySet.dates()
- [Django]-Get distinct values of Queryset by field
- [Django]-Turn off automatic pagination of Django Rest Framework ModelViewSet
6π
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 }}
- [Django]-Django DB Settings 'Improperly Configured' Error
- [Django]-How to avoid AppConfig.ready() method running twice in Django
- [Django]-How do I use a dictionary to update fields in Django models?
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
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-How to use 'select_related' with get_object_or_404?
- [Django]-Get last record in a queryset
0π
menus = Menu.objects.filter(parent__name__isnull=True)
{% for menu in menus %}
{% if menu.childs.count > 0 %}
...
{% endif %}
- [Django]-How to get the current url namespace using Django?
- [Django]-Use Django ORM as standalone
- [Django]-HTTPError 403 (Forbidden) with Django and python-social-auth connecting to Google with OAuth2