gpt4 book ai didi

python - 如何获取杂志中所有商品的价格总和? - Django ORM

转载 作者:行者123 更新时间:2023-12-01 05:55:48 24 4
gpt4 key购买 nike

class Item(models.Model):
name = models.CharField(max_length=50)
item_price = models.DecimalField(max_digits=5, decimal_places=2)

class Magazine(models.Model):
name = models.CharField(max_length=50)
items = models.ManyToManyField('Item', blank=True, null=True)
owner = models.ForeignKey(User, related_name='u_item')

如何获取杂志中所有商品的价格总和?

在 View 中:

...
user = request.user
magazins = Magazine.objects.filter(owner= user)
...

最佳答案

首先查看 aggregations in Django .

它可能如下所示:

from django.db.models import Sum
owners_magazines = Magazine.objects.filter(owner='Your owner')
total = 0;
for magazine in owners_magazines:
item_values_with_total = magazine.items.values().annotate(total=Sum('item_price'))
total += <Read appropriately from item_values_with_total>

您可以进一步尝试将事物分组在一起。返回的值将有一个名为 total 的字段,其中包含所需的总和。

编辑-

您可以尝试非 ORM 解决方案来更好地理解它

from django.db.models import Sum
owners_magazines = Magazine.objects.filter(owner='Your owner')
total = 0;
for magazine in owners_magazines:
all_items = magazines.items_set.all()
for item in all_items:
total += item.item_price

print total

关于python - 如何获取杂志中所有商品的价格总和? - Django ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12637691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com