ausi1972
ausi1972

Reputation: 23

Django sub queries

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

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()

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.

Upvotes: 1

Views: 326

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You want to use aggregation:

from django.db.models import Sum

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

Upvotes: 1

Related Questions