我的模型中存在多对一关系。我想在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)
我的问题是,如何在与sample
表的id
相关的模板中查看此键DataCollection
的数据。
这是我的模型中的示例数据,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>