【发布时间】:2019-11-19 08:20:39
【问题描述】:
我的模型中有一个多对一的关系。我想在html table中查看与父表相关的我的子表的数据。这是我的models.py:
class DataCollection(models.Model):
default_name = models.CharField(max_length=100)
class NameHistory(models.Model):
old_name = models.CharField(max_length=100)
collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True)
这是我的views.py:
def dashboard(request):
foo = ( DataCollection.objects
.annotate(
first_old_name=Window(
expression=FirstValue('namehistory__old_name'),
partition_by=[F('id'), ],
order_by=F('namehistory__id').desc()
)
)
.values_list('first_old_name', flat=True)
.distinct()
)
context = {
'sample': foo,
'dashboard': DataCollection.objects.all(),
'title':'Dashboard'
}
return render(request, 'dashboard/dashboard_form.html', context)
我的问题是,如何在与DataCollection表的id相关的模板中查看此键sample的数据。
这是我的模型中的示例数据,DataCollection:
这是NameHistory 的示例数据:
所以在我的html table 中应该是这样的:
我试过这种代码,但我不知道为什么它总是返回No Name:
<tbody>
{% for data in dashboard %}
<tr>
<td>{{ data.default_name }}</td>
{% for item in sample.namehistory_set.all %}
<td>{{ item.old_name }}</td>
{% empty %}
<td> No Name </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
【问题讨论】:
标签: django django-models orm jinja2 python-3.7