我正在使用 Coalesce
function防止聚合 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
中目的:
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)
作为最后一个值。编辑 : 如果你有一个聚合,那当然是
COALESCE
不会被评估。然后您可以使用一个简单的 or 0
在你的 Python 代码中:queryset = MyModel.objects.none()
total = queryset.aggregate(total=Sum('total')).get('total') or 0
关于如果未找到行,Django Coalesce 将返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265850/