如何解决如何在Jinja2模板Django中为“ for in”循环计算所有元素
我尝试使用循环:
user_list = <QuerySet [<TableUsers: Jane>,<TableUsers: Kate>,<TableUsers: Jons>,<TableUsers: Jacob>,<TableUsers: Jane>,<TableUsers: Jane>]>
{% for user in user_list %}
{% if user.name == "Jane" %}
{{all_count_username_jane}} # this is all count user with name Jane
{{user.name}}
{% elif user.name == "Jons" %}
{{all_count_username_jons}} # this is all count user with name Jons
{{user.name}}
{% endif %}
{% endfor %}
我如何计算所有“简”和“琼斯”?
解决方法
如果您使用的是类似user_list = SomeModel.objects.all()
的东西,则可以用类似的东西代替
from django.db.models import Count
user_list = SomeModel.objects.values('name').annotate(count_names=Count('id'))
然后还将您的模板代码更改为:
{% for user in user_list %}
{% if user.name == "Jane" %}
{{user.count_names}} # this is all count user with name Jane
{{user.name}}
{% elif user.name == "Jons" %}
{{user.count_names}} # this is all count user with name Jons
{{user.name}}
{% endif %}
{% endfor %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。