且构网

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

django模板中相关字段名称的使用

更新时间:2023-02-18 23:23:52

注意 list.bb 只会给你 RelatedManager.这里A的一个实例可以与B的多个实例相关.

所以要获得它们,您需要使用以下语法:

{% for a_obj in mylist %}{% for b_obj in a_obj.bb.all %}{{ b_obj }}{% 结束为 %}{% 结束为 %}

此处提供更多详细信息:

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

>>>b = Blog.objects.get(id=1)>>>b.entries.all() # 返回所有与博客相关的 Entry 对象.

I have tow models like below:

class A(models.Model):
    a = models.BooleanField(default=False)
    q = models.BooleanField(default=False)

class B(models.Model):
    c = models.Foreignkey('A', related_name='bb')
    d = models.BooleanField(default=False)
    e = models.BooleanField(default=False)

Here is my view:

class Myview(ListView):

    model = A
    template_name = 'admin/layer.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ListView, self).get_context_data(*args, **kwargs)
        context['mylist'] = A.objects.filter(bb__e=False)
        return context

Everything is working fine except In my template 'admin/layer.html' I am trying this:

{% for list in mylist %}
    {{ list.bb.d }}
{% endfor %}

but I do not get any value for {{ list.bb.d }} Can I use related field name in this way in django template ?

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:

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.