在django如何显示父模型数据与子模型数据在更改列表视图? [英] 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
在django 1.6.5中有没有可用的模板?
Is there some template available as this in django 1.6.5?
推荐答案
假设以下示例:
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()})
然后你的模板将是:
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 %}
对于管理界面,有一个非常好的教程 Django文档:教程:添加相关对象。
For the admin interface, there is a very good tutorial in Django documentation: Tutorial: Adding related objects.
这篇关于在django如何显示父模型数据与子模型数据在更改列表视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!