因此,我有一个名为Purchases的模型,我需要通过将所有付款加起来找到最高付费客户。找到客户在多次付款中花费最多的钱
我现在使用的方法相当迟钝,我知道它可以大规模收缩,对此最好的方法是什么?
例如:
class Purchases(models.Model):
price = models.DecimalField("Price", max_digits=18, decimal_places=2)
username = models.CharField("Username", max_length=50)
我需要查询这个模型,例如具有12个条目的所有属于customer1表,顾客2和Customer3
- customer1表具有总计为100£4个独立的付款
- Customer2有2笔独立付款,总计£75
- Customer3有6笔独立付款,总计£300
我需要找到在这个例子中花费最多的客户,它将是客户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
您需要提供更多信息。向我们展示您现在拥有的产品,样品输入/表格以及您希望输出的样子。 – 2015-02-24 14:16:32
如果你有工作代码,我会考虑把它交给http://codereview.stackexchange.com/ – user2097159 2015-02-24 14:23:00
我的代码相当丑陋,我宁愿不分享它,这让我感觉非常糟糕。 – 2015-02-24 14:25:49