简体   繁体   中英

Django count in template on object attribute

Here is a way to count objects in the django template:

{{ items|count }}

Is there a way to count objects with a certain boolean field attribute? Such as:

{{ items.boolean_field|count }} # sum([item.boolean_field for item in items])

Yes there is. Take a look at https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/

You can create a filter. Something like:

@register.filter
def count_true(value):
    return value.filter(boolean_field=True).count()

And in your template:

{{ items|count_true }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM