Chris Meek
Chris Meek

Reputation: 1523

django show object from parent table

If i have a one-to-many relationship. How do i show a field from the related parent table in my child template.

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>

Upvotes: 1

Views: 2023

Answers (1)

karthikr
karthikr

Reputation: 99620

To achieve this, you dont need to send the parent objects in the context.

You can just do {{ child.parent.name }} in the loop, where child.parent refers to the foreign key parent associated with the child model instance.

So you would just do

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

Also, you can consider optimizing the database calls using select_related or prefetch_related

Upvotes: 4

Related Questions