django模板中相关字段名的使用 [英] Use of related field name in django template

查看:35
本文介绍了django模板中相关字段名的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型如下:

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)

这是我的看法:

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

除了在我的模板 'admin/layer.html' 中,我正在尝试这个:

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

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

但是我没有得到 {{ list.bb.d }} 的任何值我可以在 django 模板中以这种方式使用相关字段名称吗?

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

推荐答案

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

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 %}

提供了更多详细信息这里:

您可以通过在 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.

这篇关于django模板中相关字段名的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆