简体   繁体   中英

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

Example: I have an Invoice as the parent model and invoice details as the child model. I would like to display the child details in the Invoice model admin as entries of the invoice. Target is to achieve a consolidated view in the listing page itself. Is there any 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 some template available as this in django 1.6.5?

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 would be as:

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 %}

For the admin interface, there is a very good tutorial in Django documentation: Tutorial: Adding related objects .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM