如何在django模板中显示父表列

时间:2016-08-27 11:21:34

标签: python django django-models django-forms django-templates

我在django中有两个模型如下:

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

我想要做的是在模板中的表格中显示来自Departments模型的id,departmentname,note和来自Directorates模型的directoratename。

以下是我的查询,需要进行编辑才能满足要求。

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

以下是表格填充的代码。

{% 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 %}

我搜索谷歌找到解决方案,但我找不到任何解决方案。请帮帮我。

1 个答案:

答案 0 :(得分:0)

您使用values()查询会让自己更难做事。只需传递对象:

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

现在你可以这样做:

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

请注意,您可以在原始查询中使用select_related来提高效率:

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

另请注意,在Django中给模型奇异名称 - Department,Directorate - 是正常的,因为实例指的是单个名称。