如果外方也没有相关数据,Django ORM group by calculation应返回数据
这是我的模型:如果外方也没有相关数据,Django ORM group by calculation应返回数据,django,django-models,django-orm,Django,Django Models,Django Orm,这是我的模型: class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name
class Purchase(models.Model):
amount = models.DecimalField(
max_digits=6,
decimal_places=2,
default=0.00
)
entry_for = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='ledger_entry_for',
)
例如,我有400多个用户,但只有50个用户购买了多次
因此,我需要用户的总购买量
下面是我的问题:
purchase_user_wise = Purchase.objects.values(
'entry_for'
).annotate(
total_purchase=Sum('amount')
)
上面的查询很好,我逐个用户返回总金额,但问题是:它只返回那些至少购买过一次或多次的用户的计算结果。此查询不会返回所有400个用户的数据
我想,如果任何用户没有任何购买条目,它应该返回0
,其余的计算应该是这样的
有人能帮我怎么做吗?你应该用相反的方法:从
用户
对象查询,并注释用户:
from django.db.models import Sum
User.objects.annotate(
total_purschase=Sum('ledger_entry_for__amount')
)
from django.db.models import Sum, Value
from django.db.models.functions import Coalesce
User.objects.annotate(
total_purschase=Coalesce(Sum('ledger_entry_for__amount'), Value(0))
)