Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we do a Sum on CharField in 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)

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.

like image 588
Bharat Bittu Avatar asked Jun 07 '18 04:06

Bharat Bittu


1 Answers

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'))
like image 186
Brown Bear Avatar answered Oct 20 '22 20:10

Brown Bear