问题
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 therelated_name
parameter in theForeignKey
definition. For example, if theEntry
model was altered toblog = 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