我们可以在Django ORM中对CharField求和吗? [英] Can we do a Sum on CharField in Django ORM?
本文介绍了我们可以在Django ORM中对CharField求和吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Django ORM中的模型是这个
My model in Django ORM is this
class Test(Modelbase):
id = models.IntegerField(null=True, blank=True)
amount = models.CharField(max_length=255)
我要为ID列表添加金额。唯一的问题是金额字段是 CharField 。如何在金额字段中应用总和?
I want to add the amount for list of id's. The only problem is the amount field is CharField. How do I apply sum for the amount field?
Test.objects.filter(id__in=[1,2,3]).aggregate(Sum('amount'))
我正在使用 Django = 1.9.1
。
推荐答案
您可以尝试<使用来对code>进行注释从django.db.models投射
you can try do annotate
with cast:
from django.db.models import FloatField
from django.db.models.functions import Cast
Test.objects.filter(id__in=[1,2,3]
).annotate(as_float=Cast('amount', FloatField())
).aggregate(Sum('as_float'))
注意用于Django< ; 1.10,您应该在
或
Note for django < 1.10, you should define Cast
here the source Cast
Or
from django.db.models import Sum, Func, F
Test.objects.annotate(
num=Func(
F('amount'),
template='%(function)s(%(expressions)s AS %(type)s)',
function='Cast', type='float')
).aggregate(Sum('num'))
这篇关于我们可以在Django ORM中对CharField求和吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文