Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: objects and model_set

Tags:

python

django

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()
like image 355
Emmanuel Mtali Avatar asked Dec 23 '22 23:12

Emmanuel Mtali


1 Answers

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.

like image 180
user4426017 Avatar answered Jan 09 '23 00:01

user4426017