开发者

Django sub queries

I have a basic database that I want to pull out sub data (related) in the same view:

models.py:

class I开发者_JAVA百科nvoiceHeader(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()

What I am trying to get is the invoice total in the list_invoices view which would consist of the invoicelines.price (totalled) for each invoiceheader such that in the template I can just put:

{% for invoice in invoices %}
    {{ invoice.subtotal }}
{% endfor %}

I think it is something to do with def something in the models.py file but I am getting lost with this.

So any help would be much appreciated.


You want to use aggregation:

from django.db.models import Sum

def list_invoices(request):
    invoices = Item.objects.all().annotate(subtotal=Sum('invoiceline__price'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜