14

In the Django tutorial:

 {% for choice in question.choice_set.all %} 

I couldn't find a brief explanation for this. I know that in the admin.py file, I have created a foreign key of Question model on the choice model such that for every choice there is a question.

3
  • 1
    take a look here: stackoverflow.com/questions/2048777/… I was looking for it a few minutes ago ;-) Commented Jul 31, 2015 at 12:55
  • the .all is the same 'all' as when you do Choice.objects.all() i.e. the queryset method. see @wim's answer for why Commented Jul 31, 2015 at 13:28
  • @Tom83B +1 for pointing to the right question with nice explanation. Commented Mar 12, 2020 at 15:28

1 Answer 1

29

That's the Django metaclass magic in action! Since you have a foreign key from Choice model to the Question model, you will automagically get the inverse relation on instances of the question model back to the set of possible choices.

question.choice_set.all is the queryset of choices which point to your question instance as the foreign key.

The default name for this inverse relationship is choice_set (because the related model is named Choice). But you can override this default name by specifying the related_name kwarg on the foreign key:

class Choice(models.Model): ... question = models.ForeignKey(Question, related_name='choices') 
Sign up to request clarification or add additional context in comments.

2 Comments

@wim good explanation, thanks. This is really confusing in the Django tutorial documentation, because you're initially working with two db class models called Question and Choice, so choice_set.all makes you think there should be a method in your Choice class called choice_set or something.
This seems like a great place to update and improve the (already excellent) documentation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.