找出哪些客户在多次付款中花费最多

2024-06-17 15:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个叫做购买的模型,我需要把所有的付款加起来,找出谁是支付最高的客户。你知道吗

我目前的方法是相当迟钝,我知道它可以大量缩小,这将是最好的方法呢?你知道吗

例如:

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

  • Customer1有4笔单独付款,总计100英镑
  • Customer2有2笔单独付款,总计75英镑
  • Customer3有6笔单独付款,总计300英镑

我需要找到花费最多的客户在本例中是customer3,总花费价值为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

Tags: 方法模型self客户modelstopusernamecustomer
2条回答

我认为你应该定义一些函数,比如:

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]

说明: 对于所有用户,我们汇总他们的重新购买集并计算购买价格之和,然后按最大的购买集和订购,并用[0]获得第一个

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

相关问题 更多 >