Use of related field name in django template

旧街凉风 提交于 2020-07-11 04:28:31

问题


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 ?


回答1:


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.


来源:https://stackoverflow.com/questions/37018886/use-of-related-field-name-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!