从Int到Float的Django Sum聚合

时间:2018-01-04 11:50:27

标签: django django-models django-queryset

所以我以美分节省我的费用,但希望以欧元显示。转换问题是它首先将整数除以100,然后转换为float。它应该是相反的方式。我怎么能这样做?

以下代码应说明我的问题:

>>> from django.db.models import F, FloatField, Sum
>>> from payment.models import Payment
>>> 
>>> paymentlist = Payment.objects.all()
>>> result = paymentlist.annotate(
...     fees_in_cents=Sum(F('fees'), output_field=FloatField())).annotate(
...         fees_in_euro=Sum(F('fees')/100, output_field=FloatField()))
>>> 
>>> print(result[0].fees_in_cents, result[0].fees_in_euro)
120.0 1.0
费用_in_euro显然应该是1.20

1 个答案:

答案 0 :(得分:2)

将费用值除以100.0

示例

result = paymentlist.annotate(
    fees_in_cents=Sum(F('fees'), output_field=FloatField())).annotate(
    fees_in_euro=Sum(F('fees') / 100.0, output_field=FloatField())
)