I am new to Django. I would like to count and display the number of objects which satisfy a condition in a template.
I have a User model and Account model. The users have a foreignkey field account, which maps onto an Account object.
In the template, I would like to count the number of users for each account.
The closest I have got is this:
{% for account in accounts %}
{% for user in users %}
{% if equal user.account.id account.id %}
{{ user.count }}
{% endif %}
{% endfor %}
{% endfor %}
Thanks
From your template, it seems like the user field is defined something like this:
class User(models.Model):
.
.
account=models.Foreignkey()
.
if it is something like this you could follow this.
{% for account in accounts %}
Count: {{ account.user_set.count }}
{% for user in account.user_set.all %}
{{ user }}
{% endfor %}
{% endfor %}
You can annotate your accounts with the user count in the view. Assuming the User model contains account = ForeignKey(Account, related_name='users'):
accounts = Account.objects.annotate(user_count=models.Count('users'))
That way you'll only need a single query. Then simply use the following in your template:
{% for account in accounts %}
{{ account.user_count }}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With