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

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

问题描述

我有如下两个模型:

A 类(models.Model):a = models.BooleanField(默认=假)q = models.BooleanField(默认=假)B类(模型.模型):c = models.Foreignkey('A',related_name='bb')d = models.BooleanField(默认=假)e = models.BooleanField(默认=假)

这是我的观点:

class Myview(ListView):模型 = A模板名称 = 'admin/layer.html'def get_context_data(self, *args, **kwargs):context = super(ListView, self).get_context_data(*args, **kwargs)上下文['mylist'] = A.objects.filter(bb__e=False)返回上下文

一切正常,除了在我的模板admin/layer.html"中,我正在尝试:

{% for list in mylist %}{{ list.bb.d }}{% 结束为 %}

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

解决方案

注意 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.

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

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