Can we do a Sum on CharField in Django ORM?

前端 未结 1 1768
庸人自扰
庸人自扰 2020-12-19 06:34

My model in Django ORM is this

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


        
相关标签:
1条回答
  • 2020-12-19 06:55

    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'))
    
    0 讨论(0)
提交回复
热议问题