找出客户在多次付款中花费最多的钱

Find what customer has spent the most money across multiple payments

所以我有一个名为 Purchases 的模型,我需要通过将所有付款相加来找出谁是付费最高的客户。

我目前的方法比较落后,我知道它可以大量缩小,请问最好的方法是什么?

例如:

class Purchases(models.Model):
    price = models.DecimalField("Price", max_digits=18, decimal_places=2)
    username = models.CharField("Username", max_length=50)

我需要查询这个模型,例如有 12 个条目都属于 Customer1、Customer2 和 Customer3

在此示例中,我需要找到花费最多的客户,即客户 3,总花费价值为 300 英镑。

这是我刚想出的代码示例,但我知道它可以大大改进:

def find_top_customer(self)
    top_donor = None
    spent = None
    for customer in Purchase.objects.filter(marketid=self.marketid):
        customer_spent = Purchase.objects.filter(marketid=self.marketid,username=customer.username).aggregate('price')[0]
        if customer_spent > spent:
            top_donor = customer.username
            spent = customer_spent

我认为您应该定义一些函数,例如:

allPurchases(client)
findPurchase(id, client)

并使用这些来获取您想要的数据。

好的,我已经弄明白了,抱歉回答不好...(代码测试)

如果您在购买模型中有用户的外键:

class Purchase(models.Model):
    price = models.DecimalField("Price", max_digits=18, decimal_places=2)
    user = models.ForeignKey('auth.User', related_name='purchase_set')

您可以通过这种方式获得最多的购买用户:

from django.db.models import Sum
most_purchasing_user = User.objects.annotate(purchase_sum=Sum('purchase_set__price')).order_by('-purchase_sum')[0]

解释: 对于所有用户,我们汇总他们 purchase_set 并计算购买价格的总和,然后我们 order_by 最大的 purchase_set 总和,并得到第一个 [0]

警告 这对数据库来说是一个很大的开销,你应该考虑将结果放在缓存中 Django Cache Framework