2👍
✅
This is how you fetch the questions:
q = Survey.objects.get(id=1)
q.question_set.all()
Here’s the relevant docs section.
You can also set related_name
to your FK field like:
survey = models.ForeignKey(Survey, related_name='questions')
this makes accessing questions more meaningful:
q = Survey.objects.get(id=1)
q.questions.all()
Remember to use get
instead of filter
(filter
returns list of objects instead of single object).
Finally by using what we’ve learned, you can now change your custom method like so:
def questions(self):
if self.pk:
return self.questions.all()
else:
return None
Source:stackexchange.com