Django 查询字典对应的值

Django query to dict with corresponding values

我正在做一个商店项目,希望能够看到我商店中最畅销的产品是什么。

这是我的 models.py

class Product(models.Model):
    #some values like name, price, etc...

class Purchase(models.Model):
    purchase_completed = models.BooleanField(default=False)
    # This is the only important field for this model regarding the problem that I Have
    # Other fields include stuff like buyers info, end price, etc...


class PurchaseContains(models.Model):
    #Every product has its amount, purchase its related to and the product of course, with some other values as well, but not related to the problem I'm having 
    product = models.ForeignKey(Product...) 
    purchase = models.ForeignKey(Purchase...)
    amount = models.PositiveIntegerField(blank=False, null=False)

现在我想要的是做一个查询,它会给我 PurchaseContains 中的 Products 购买最多的东西(table 中的 amountPurchase 本身也必须完成(对于 PurchaseContains 中的给定产品,Purchase 中的 purchase_completed==True

现在这是我所做的:

sold_the_most= PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product", 'amount')
sold_the_most_dict= {}
for i in sold_the_most:
    sold_the_most_dict[i["product"]] = sold_the_most_dict.get(i['product'], 0)+i["amount"]

如您所见,我获得了已完成购买的 productsamount,然后对其进行循环以将它们放入字典中。

现在这确实有效,它为我提供了我可以使用的输出,但我确信有更好的解决方案。一些查询可能会以类似于 [[product, amount], [product, amount], ...] 的形式给我数据(没想到会马上这样,但你明白了)。

我已经搜索了很长时间,你看到的解决方案是我想出的最好的解决方案,因为我对 Django 查询不太熟悉。

可能您想要 SQL 中的 GROUP_BY 之类的东西。可以在 Django 中使用 aggregation features of the ORM:

来做到这一点
from django.db.models import Sum

values = PurchaseContains.objects.filter(purchase__purchase_completed=True).values("product").annotate(total=Sum("amount")).values('product','total')
print(values)