【问题标题】:Django: Relational view in template [many-to-one relationship]Django:模板中的关系视图[多对一关系]
【发布时间】: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


    【解决方案1】:

    您应该为仪表板/表格使用带注释的查询集,因为它将在每个对象上注释旧名称

    foo = DataCollection.objects.annotate(
        first_old_name=Window(
            expression=FirstValue('namehistory__old_name'),
            partition_by=[F('id'), ],
            order_by=F('namehistory__id').desc()
        )
    )
    context = {
        'dashboard': foo,
        'title':'Dashboard'
    }
    

    然后在你的模板中

    <tbody>
    {% for data in dashboard %}
    <tr>
        <td>{{ data.default_name }}</td>
        <td>{{ data.first_old_name:default"No Name" }}</td>
    </tr>
    {% endfor %}
    </tbody>
    

    【讨论】:

    • 我遇到了错误,Could not parse the remainder: ':default"No Name"' from 'data.first_old_name:default"No Name"'
    • 我试图删除`default"No Name"`。 .然后我明白了。 .
    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2014-05-20
    • 2021-02-23
    • 2013-11-05
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多