Can we do a Sum on CharField in Django ORM?

孤街浪徒 提交于 2019-12-05 13:33:03

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