Django -将queryset的结果除以整数

11dmarpk  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(168)

我是Django的新手,对此我有点困惑。我有一个视图,它显示了一个十进制字段的总和(金额),按外键的名称分组(账户计划):

def projection(request):
    divider = int(date.today().strftime('%d'))
    qs = ManagerialRevenue.objects.values('accountplan__name').annotate(Sum('amount'))

    return render(request, 'app/pages/planning/projection.html', context={'qs': qs,})

我需要将qs变量中的每个带注解的金额字段除以divider变量。

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
{% endfor %}

但当我尝试将值除时,会在视图中添加以下行:

result = qs / divider

并在模板中循环使用:

{% for item in result %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
{% endfor %}

它显示了一个 * 不支持的/操作数类型:'QuerySet'和'int'* 错误.我理解错误(或者至少我是这么认为的),并试图在视图中这样循环:

for result in qs:
    result / divider

但是我仍然得到字典的结果,和上面一样的错误,除了 'dict'和'int'
有办法做到这一点吗?谢谢!

n6lpvg4x

n6lpvg4x1#

要进行除法运算,请使用**widthratio**模板标记

# views.py

def projection(request):
    divider = int(date.today().strftime("%d"))
    qs = ManagerialRevenue.objects.values("accountplan__name").annotate(Sum("amount"))

    return render(
        request,
        "app/pages/planning/projection.html",
        context={"qs": qs, "divider": divider},
    )


# template.html

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
    {% widthratio item.amount__sum divider 1 %}{{ item.amount__sum }}
{% endfor %}

或者,您甚至可以更新qs变量,以保存除法结果

views.py

def projection(request):
    divider = int(date.today().strftime("%d"))
    qs = ManagerialRevenue.objects.values("accountplan__name").annotate(Sum("amount"))
    qs_updated = [{**item, "div_result": item["amount__sum"] / divider} for item in qs]
    return render(
        request,
        "app/pages/planning/projection.html",
        context={"qs": qs_updated},
    )

# template.html

{% for item in qs %}
    {{ item.accountplan__name }}
    {{ item.amount__sum }}
    {{ item.div_result }}
{% endfor %}

相关问题