Ajmal Amirzad Ajmal Amirzad - 3 months ago 19
Python Question

How to display parent table columns in django template

I have two models in django as below:

class Directorates(models.Model):
entrydate = models.DateTimeField(auto_now=True)
directoratename = models.CharField("Directorate", max_length=1000)
note = models.CharField("Note", max_length=2000, null=True)
insertedby = models.IntegerField(null=False)
updatedby = models.IntegerField(null=False, default='0')
deletedby = models.IntegerField(null=False, default='0')

def __str__(self):
return self.directoratename


class Departments(models.Model):
entrydate = models.DateTimeField(auto_now=True)
departmentname = models.CharField("Department", max_length=1000)
note = models.CharField("Note", max_length=2000, null=True)
directorate = models.ForeignKey(Directorates, on_delete=models.CASCADE)
insertedby = models.IntegerField(null=False)
updatedby = models.IntegerField(null=False, default='0')
deletedby = models.IntegerField(null=False, default='0')

def __str__(self):
return self.departmentname


What I want to do is to display id, departmentname, note from Departments model and directoratename from Directorates model in a table in template.

Below is my query which needs to be edited to meet the requirements.

Departments.objects.filter(deletedby=0).values("id", "departmentname", "note", "directorate_id").order_by('-id')[:5]


Below is the code for table population.

{% for d in data %}
<tr>
<td>{{ d.departmentname }}</td>
<td>directoratename to be displayed here.....</td>
<td>{{ d.note }}</td>
<td class="pull-right">
<form action="{% url 'app:departments-delete' d.id %}" method="post">
{% csrf_token %}
<div class="btn-group" role="group" aria-label="...">
<a href="{% url 'app:departments-edit' d.id %}" class="btn btn-warning glyphicon glyphicon-pencil"></a>
<button type="submit" class="btn btn-danger glyphicon glyphicon-trash"></button>
</div>
</form>
</td>
</tr>
{% endfor %}


I searched google to find the solution for this however I couldn't find any solution for this. Please help me.

Answer

You're making things harder for yourself by using a values() query. Just pass the objects themselves:

departments = Departments.objects.filter(deletedby=0)

and now you can do:

{% for d in data %}
  <tr>
    <td>{{ d.departmentname }}</td>
    <td>{{ d.directorate.directoratename }}</td>

Note that you can make this more efficient by using select_related in the original query:

departments = Departments.objects.filter(deletedby=0).select_related('directorate')

Also note that it is normal in Django to give the models singular names - Department, Directorate - because an instance refers to a single one.