且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django模板中使用相关字段名称

更新时间:2023-02-18 23:37:15

请注意,list.bb仅会给您

Note that list.bb will only give you the RelatedManager. Here an instance of A can be related to multiple instances of B.

因此,要获取所有内容,您需要使用以下语法:

So to get them all you need to use following syntax:

{% for a_obj in mylist %}
    {% for b_obj in a_obj.bb.all %}
        {{ b_obj }}
    {% endfor %}
{% endfor %}

提供了更多详细信息此处 :

More details provided here:

您可以通过在ForeignKey定义中设置related_name参数来覆盖FOO_set名称.例如,如果将Entry模型更改为blog = ForeignKey(Blog, on_delete=models.CASCADE, related_name='entries'),则上面的示例代码将如下所示:

You can override the FOO_set name by setting the related_name parameter in the ForeignKey definition. For example, if the Entry model was altered to blog = ForeignKey(Blog, on_delete=models.CASCADE, related_name='entries'), the above example code would look like this:

>>> b = Blog.objects.get(id=1)  
>>> b.entries.all() # Returns all Entry objects related to Blog.

推荐文章