django 模型从外键关系求和字段

标签 django django-models

我有一对多的关系。

class Invoice(models.Model):
    stuff

class Item(models.Model):
    invoice = models.ForeignKey(Invoice)
    qty = models.IntegerField()
    unit_price = models.DecimalField(max_digits=4, decimal_places=2)

我想查询以选择发票中的所有行以及每张发票的所有项目的价格总和,并通过查询集访问它

例如
所以如果 invoice #12 items , 每个都带有 qty=2unit_price=3 , invoice #1会有 amount 2x2x3 = $12
更新:

这是我到目前为止所拥有的,但它给了我一个追溯
inv_list = \
Invoice.objects.select_related().all()\
.aggregate(sum=sum('item__unit_price')).order_by('-inv_date')

TypeError at /site/invoice/
unsupported operand type(s) for +: 'int' and 'str'

更新

感谢您的输入,我参加了一些队列,最后我创建了一个新专栏 unit_amount , 为 .save() 添加了一个额外的操作方法做prod_qty * unit_price并将其保存到新列。

然后这样做:
inv_list = Invoice.objects.all()\
.annotate(amount=Sum('item__unit_amount')).order_by('-inv_date')

最佳答案

for invoice in Invoice.objects.all():
    ammount = 0
    for item in invoice.item_set.all():
        ammount += item.qty * item.unit_price
        print invoice.pk, ammount

关于django 模型从外键关系求和字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7725861/

相关文章:

python - django.core.exceptions.ImproperlyConfigured : Cannot import 'category' . 检查 'api.category.apps.CategoryConfig.name'是否正确

python - 从 get_or_create 结果分配时,ForeignKey 不会保存

python - 名称错误 : name 'LoginView' is not defined

python - 无法从登录页面进一步移动,[django-otp]

django - 在Django过滤器语句中,__exact和等号(=)有什么区别?

python - 尝试创建寄存器 View 时出现 NOT NULL 约束失败错误

python - Django CharField 在不应该的时候接受空值

python - 使用嵌套对象在 ModelViewSet 上发布 Django Rest Framework

python - 截断字符的 Django 过滤器是什么?

python - 如何编写适用于Python 2和Python 3的代码?