如果我有一个一对多的关系。我如何在我的子模板中显示相关父表中的字段。
模型.py
class Parent(models.Model):
name = models.CharField()
class Child(models.Model):
parent = models.ForeignKey(parent)
child_name = models.CharField()
View .py
def childs(request):
return render_to_response('dashboard/childs.html', {'childs': Child.objects.all(), 'parents': Parent.objects.all() })
child .html
<table class="table table-striped">
<thead>
<tr>
<th>id</th>
<th>child name</th>
<th>parent name</th>
</tr>
</thead>
<tbody>
{% for child in childs %}
<tr>
<td><a href="/parent/get/childs/{{ child.id }}/">{{ child.id }}</a></td>
<td><a href="/parent/get/{{ child.id }}/">{{ child.child_name }}</a></td>
<td><a href="/parent/get/{{ child.id }}/">{{ parent.name }}</a></td>
最佳答案
为此,您不需要在上下文中发送 parent
对象。
你可以在循环中执行{{ child.parent.name }}
,其中child.parent
指的是外键parent
与 child
模型实例关联。
所以你会做
<a href="/parent/get/{{ child.parent.id }}/">{{ child.parent.name }}</a>
此外,您可以考虑使用 select_related
优化数据库调用或 prefetch_related
关于python - django 显示来自父表的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25836626/