boost django汇总对象列表。 groupby和agg为django

问题描述 投票:0回答:1

我有一个模型,并使用Django查询从中获取数据。

class carts:
    product_id =  models.foreginkey('Product')
    count = models.IntegerField()
    price = models.IntegerField()

我需要商品总价:

list_of_prices = []
for product in products:
    list_of_prices.append(carts.objects.filter(product_id=product.id)\
                  .aggregate(total_price=Sum(F(count) * F(price))))

有没有没有for循环的方法list_of_prices?只用一两个查询就可以获取它吗?我需要一些行为,例如groupby,然后是aggpandas

python django django-queryset django-orm
1个回答
0
投票

您可以在models.py中编写一个函数,并直接从对象中使用它

class carts:
    product_id =  models.foreginkey('Product')
    count = models.IntegerField()
    price = models.IntegerField()

    def total_price(self):
        return self.count * self.price

然后

list_of_prices = []
for product in products:
    cart = carts.objects.filter(product_id=product.id)
    list_of_prices.append(cart.total_price)
© www.soinside.com 2019 - 2024. All rights reserved.