Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is choice_set.all in Django tutorial

Tags:

python

django

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.

like image 851
Bolshoi Booze Avatar asked Jul 31 '15 12:07

Bolshoi Booze


1 Answers

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')
like image 117
wim Avatar answered Oct 23 '22 08:10

wim