Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django显示父表中的对象_Python_Django - Fatal编程技术网

Python django显示父表中的对象

Python django显示父表中的对象,python,django,Python,Django,如果我有一对多的关系。如何在子模板中显示相关父表中的字段 models.py class Parent(models.Model): name = models.CharField() class Child(models.Model): parent = models.ForeignKey(parent) child_name = models.CharField() views.py def childs(request): return render_t

如果我有一对多的关系。如何在子模板中显示相关父表中的字段

models.py

class Parent(models.Model):
    name = models.CharField()

class Child(models.Model):
    parent = models.ForeignKey(parent)
    child_name = models.CharField()
views.py

def childs(request):
    return render_to_response('dashboard/childs.html', {'childs': Child.objects.all(), 'parents': Parent.objects.all() })
childs.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>

要实现这一点,不需要在上下文中发送父对象

您可以在循环中执行{{child.parent.name},其中child.parent引用与子模型实例关联的外键父级

那你就这么做吧

<a href="/parent/get/{{ child.parent.id }}/">{{ child.parent.name }}</a>

此外,您可以考虑使用或使用< /P> > P>优化数据库调用,以实现这一点,不需要在上下文中发送父对象。

您可以在循环中执行{{child.parent.name},其中child.parent引用与子模型实例关联的外键父级

那你就这么做吧

<a href="/parent/get/{{ child.parent.id }}/">{{ child.parent.name }}</a>

此外,可以考虑使用“或”/P> @ CurZiff-OP优化数据库调用,而不是反向查找。@ CurZixOP不进行反向查找。