Can we do a Sum on CharField in Django ORM?

邮差的信 提交于 2019-12-12 09:41:49

问题


My model in Django ORM is this

class Test(Modelbase):
    id = models.IntegerField(null=True, blank=True)
    amount = models.CharField(max_length=255)

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'))

I am using Django=1.9.1 for this.


回答1:


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'))

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'))


来源:https://stackoverflow.com/questions/50733159/can-we-do-a-sum-on-charfield-in-django-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!