In django How to display parent model data with child model data in change list view?

Example. I have an invoice as a parent model and invoice details as a child model. I would like to display child details in the invoice model as invoice records. The goal is to get a consolidated view on the listing page itself. Is there an alternative to achieve this: it should look like this:

Invoice 1: -details 1 -details 2 Invoice 2: -details 1 -details 2 -details 3 

Is there any template available as in django 1.6.5?

0
source share
1 answer

Assume the following example:

models.py

 class Invoice(models.model): date = models.DateTimeField() # for example class InvoiceDetail(models.model): invoice = models.ForeignKey(Invoice) 

views.py

 # example, don't fetch all in production return render(request, 'mytemplate.html', {'invoices': Invoice.objects.all()}) 

Then your template will look like this:

mytemplate.html

 {% for invoice in invoices %} <p>Invoice {{ invoice.id }} ({{ invoice.date }}) {% if invoice.invoicedetail_set %} <ul> {% for detail in invoice.invoicedetail_set %} <li>Detail {{ detail.id }}</li> {% endfor %} </ul> {% endif %} </p> {% endfor %} 

There is a very good tutorial for the admin interface in the Django Documentation: Tutorial: Adding Related Objects .

+2
source

All Articles