Reputation: 1109
I have 2 models defined as follows:
class Article(models.Model):
url = models.URLField(max_length=200, unique=True, null=False)
title = models.CharField(max_length=200, unique=False, null=False)
class List(models.Model):
article = models.ForeignKey(Article, related_name='joining')
list = models.IntegerField(default=0, null=False, unique=False)
Querying the Article
class InboxView(SomeMixin, generic.ListView):
template_name = '...'
context_object_name = 'article_list'
def get_queryset(self):
return Article.objects.all().prefetch_related('joining')
On my template, this works:
{% for article in article_list %} {{ article.title }} {% endfor %}
But this does not
{% for article in article_list %} {{ article.list }} {% endfor %}
Upvotes: 1
Views: 67
Reputation: 11591
You will need this instead:
{% for article in article_list %}
{{ article.title }}
{% for t in article.joining.all %}
{{ t.list }}
{% endfor %}
{% endfor %}
Since you are iterating through the "other" side of the relationship (i.e. articles), you will access each article's related List
via the article's list_set (to which you have given the related name 'joining').
Incidentally, you might want to find a different name for your List
model. It makes this discussion somewhat confusing.
Upvotes: 1
Reputation: 2945
You can not access child.field this way. If your parent child are properly referenced, you have to do like:
{% for parent in parent_list %}
my parent value: {{parent.field1}}
{%for child in parent.child_set.all %}
My child value {{child.field2}}
{%endfor%}
{%endfor%}
Thanks
Upvotes: 1