如果没有找到行,Django Coalesce 返回 null

2024-02-28

我正在使用Coalesce功能 https://docs.djangoproject.com/en/dev/ref/models/database-functions/#coalesce以防止聚集Sum从返回None

Coalesce(Sum('ext_price'), 0)

问题是,如果没有找到行,它仍然返回 null。有没有办法修改该函数,以便在未找到行时返回零?

class Coalesce(Func):
    """Return, from left to right, the first non-null expression."""
    function = 'COALESCE'

    def __init__(self, *expressions, **extra):
        if len(expressions) < 2:
            raise ValueError('Coalesce must take at least two expressions')
        super().__init__(*expressions, **extra)

我的意思是没有行

queryset = MyModel.objects.none()
total = queryset.aggregate(total=Coalesce(Sum('total'), Value(0)).get('total')
total == None  # True

您需要将值包装在Value object:

from django.db.models import Coalesce, Value

Coalesce(Sum('ext_price'), Value(0))

您可以实施自己的Coalesce函数,例如:

from django.db.models import Value
from django.db.models.functions import Coalesce

class CoalesceZero(Coalesce):

    def __init__(self, *expressions, **extra):
        super().__init__(*expressions, Value(0), **extra)

在这种情况下,您可以使用您的CoalesceZero,你不再需要写Value(0)作为最后的值。

EDIT:如果你有一个聚合,那当然是COALESCE不会被评估。然后你可以使用一个简单的or 0在你的Python代码中:

queryset = MyModel.objects.none()
total = queryset.aggregate(total=Sum('total')).get('total') or 0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果没有找到行,Django Coalesce 返回 null 的相关文章

随机推荐