【问题标题】:How to count the number of resuts of an if on Django built in templates如何在Django内置模板上计算if的结果数
【发布时间】:2017-11-21 21:08:05
【问题描述】:

我有以下情况:

{% for subject in subjects %}
    {% if subject.media < 60 %}
        {{ subjects|length }}
    {% endif %}
{% endfor %}

结果是“161616”,因为我的数据库中有 16 个主题,但我想显示低于媒体的主题数量,例如“3”。

【问题讨论】:

    标签: python django django-template-filters


    【解决方案1】:

    你不能在模板中做这样的逻辑。在视图中进行查询

    def my_view(request):
        num_under_60 = Subject.objects.filter(media__lt=60).count()
        return render(request, 'my_template.html', {'num_under_60': num_under_60})   
    

    然后在模板中使用{{ num_under_60 }}

    【讨论】:

    • 此查询将返回对象,您需要对它们进行计数,如下所示:num_under_60 = len(Subject.object.filter(media__lt=60)) 谢谢,成功了。
    • 很好,我已经更新了答案以使用.count()
    【解决方案2】:

    我认为你应该写{{ subject|length }} 而不是{{ subjects|length }}

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 2016-06-26
      • 2020-10-02
      • 2017-08-10
      • 2021-07-22
      • 2021-11-01
      相关资源
      最近更新 更多