Django ORM组通过计算应该返回数据,如果国外没有相关数据也是如此。

问题描述 投票:1回答:1

这是我的模型。

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 和其余的计算应该是这样的工作。

有谁能帮助我如何能做到这一点?

django django-models django-orm
1个回答
2
投票

你应该用相反的方式来做:查询从 User 对象,以及 注释 的用户。

from django.db.models import Sum

User.objects.annotate(
    total_purschase=Sum('ledger_entry_for__amount')
)

这将返回一个由 User 对象,而每个 User这个 queryset将有一个额外的属性。.total_purchase.

如果用户没有进行购买,那么金额将是。None (NULL). 您可以使用 Coalesce 表达式 [Django-doc] 使用 0 而不是。

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))
)
© www.soinside.com 2019 - 2024. All rights reserved.