Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting objects in Django template

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

like image 651
eli Avatar asked Feb 21 '26 12:02

eli


2 Answers

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 %}
like image 154
crodjer Avatar answered Feb 26 '26 01:02

crodjer


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 %}
like image 21
emulbreh Avatar answered Feb 26 '26 00:02

emulbreh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!