Django query for many-to-one relationships

I have three models, one topic can have zero or more questions, one question can have zero or many answers. Only one answer is correct.

They have a lot of relationships.

class Topic(models.Model): class Question(models.Model): topic = models.ForeignKey(Topic) class Answer(models.Model): question = models.ForeignKey(Question) isright = models.BooleanField(verbose_name='Right') 

Now I tried to ask a question based on the topic, how can I achieve it with a template?

 <topic> <question> <answer> <answer> <answer> <answer> <question> <answer> <answer> <answer> <answer> 

How can I add a paginator for the question?

 paginator = Paginator(topic.question_set.all(), 25) 
+4
source share
3 answers

If I understand well, you want to program the answers sorted by topic:

 answers = Answer.objects.order_by('question__topic', 'question') 

or

 for topic in Topic.objects.all(): for question in topic.question_set.all(): for answer in question.answer_set.all(): ...do something... 

In templates, you can do the same by providing the topics variable as Topic.objects.all ():

 {% for topic in topics %} {% for question in topic.question_set.all %} {% for answer in question.answer_set.all %} ...do something... {% endfor %} {% endfor %} {% endfor %} 
+5
source

Use the variable * _set.all ():

  t = Topic.objects.get(id=X) questions = t.question_set.all() for q in questions: answers = q.answer_set.all() for a in answers: print a 
+1
source
 topic_instance.question_set.all() 

See docs

0
source

All Articles