I am learning django 1.10 official tutorial part 2
class Question(models.Model):
# ......
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
#.......
Recent i saw the following command:-
q = Question.objects.get(id=1)
q.choice_set.all()
My questions:-
How Question instance contain choice_set
, i know it for accessing related objects.
Why is this not valid
c = Choice.objects.get(id=1)
c.question_set.all()
The Question model does not have an explicit reference to the Choice model; however, Django automatically adds a reverse-reference, which is by default called choice_set. You can override this by related_name keyword on the model such as:
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
Now you can reference all of the choices for a question like this:
q = Question.objects.get(pk=1)
q.choices.all()
To answer your second question, the reason you cannot use reference question_set.all() from a choice object is because for each choice, there is only one question plus there is an explicit reference to the question object. In other words the Choice model already has a field called Question, which points to the Question model.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With