Django: get the number of ForeignKey elements in a template?

The simple question is apologies if it is a duplicate, but I cannot find an answer if that is the case.

I have a user model and a presentation model, for example:

class Submission(models.Model):
    uploaded_by = models.ForeignKey('User')
class User(models.Model):
    name = models.CharField(max_length=250 )

How can I show the number of posts made by each user in the template ? I tried {{ user.submission.count }}for example:

for user in users:
    {{ user.name }} ({{ user.submission.count }} submissions)

but no luck ...

+3
source share
2 answers

try it

{{user.submission_set.all|length}}
+6
source

You forgot to "install." It should be {{ user.submission_set.count }}. You can always change the corresponding name, but this is the default <fk class name>_set. See relationship documentation for more details .

+2
source

Source: https://habr.com/ru/post/1740680/


All Articles