所以我有一个叫做购买的模型,我需要把所有的付款加起来,找出谁是支付最高的客户。你知道吗
我目前的方法是相当迟钝,我知道它可以大量缩小,这将是最好的方法呢?你知道吗
例如:
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
我需要找到花费最多的客户在本例中是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
我认为你应该定义一些函数,比如:
用这些来获得你想要的数据。你知道吗
好吧,我想好了,抱歉回答不好。。。(代码测试)
如果您的购买模型中有一个用户外键:
您可以通过以下方式获得最具购买力的用户:
说明: 对于所有用户,我们汇总他们的重新购买集并计算购买价格之和,然后按最大的购买集和订购,并用[0]获得第一个
警告 这对数据库来说是一个很大的开销,你应该考虑把结果放到缓存中 Django Cache Framework
相关问题 更多 >
编程相关推荐