我们可以在 Django ORM 中对 CharField 进行求和吗?

Bha*_*ttu 9 django django-orm

我在 Django ORM 中的模型是这样的

class Test(Modelbase):
    id = models.IntegerField(null=True, blank=True)
    amount = models.CharField(max_length=255)
Run Code Online (Sandbox Code Playgroud)

我想添加 id 列表的数量。唯一的问题是金额字段是CharField。如何为金额字段申请金额?

Test.objects.filter(id__in=[1,2,3]).aggregate(Sum('amount'))
Run Code Online (Sandbox Code Playgroud)

我正在Django=1.9.1为此使用。

Bea*_*own 10

您可以尝试annotate使用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'))
Run Code Online (Sandbox Code Playgroud)

注意django < 1.10,你应该Cast在这里定义源 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'))
Run Code Online (Sandbox Code Playgroud)