1

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 %} 
3
  • Are the models related? Commented Jun 8, 2014 at 0:20
  • Yes, field2 in Child references Parent Commented Jun 8, 2014 at 0:21
  • What kind of relationship is it? (You might just show your models.) Commented Jun 8, 2014 at 0:27

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It still prints article.title but not t.list
BTW I have specified how I write the query in more details
@user1477118 Ah, I see! You have given a related_name to your foreign_key. Instead of list_set you will use joining instead. Try the above code in my updated answer.
@user1477118 Great! I'm glad you got it figured out.
1

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

2 Comments

I have updated the question, so now what would I write instead of parent.child in the second loop? Thank you!
Since your parent (Article) consist many child (List), you should do a for loop. You have one-to-many relation. If don't want to do that change youe module for one-to-one relation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.