我有一个基本数据库,我想在同一视图中提取子数据(相关):
models.py:
class InvoiceHeader(models.Model):
customer = models.CharField(max_length = 255)
number = models.IntegerField(unique = True)
class InvoiceLine(models.Model):
description = models.CharField(max_length = 255)
price = models.DecimalField(max_digits = 10, decimal_places = 2)
invoiceheader = models.ForeignKey(InvoiceHeader)
views.py:
def list_invoices(request):
invoices = InvoiceHeader.objects.all()
我想要得到的是list_invoices视图中的发票总额,其中包含每个发票人的invoicelines.price(总计),以便我可以在模板中添加:
{% for invoice in invoices %}
{{ invoice.subtotal }}
{% endfor %}
我认为这与models.py文件中的def有关,但我对此感到迷茫。
所以任何帮助都会非常感激。
答案 0 :(得分:1)
您想使用aggregation:
from django.db.models import Sum
def list_invoices(request):
invoices = Item.objects.all().annotate(subtotal=Sum('invoiceline__price'))