简体   繁体   中英

Django MultiDimensional Queryset on Related objects

I'm a Django newbie and I created a quiz application. I'm wondering if it's possible to do just a single query and get a multi-level queryset for three related tables.

A Quiz has multiple questions and a question has multiple choices.

quizzes/models.py:

class Quiz(models.Model):
    title = models.CharField(max_length=200)

class Question(models.Model):
    quiz_id = models.ForeignKey("Quiz", db_column="quiz_id")
    question = models.TextField()

class Choice(models.Model):
    question_id = models.ForeignKey("Question", db_column="question_id")
    text = models.TextField()

The result I'm expecting is something like this:

[{
quiz_id:1,
quiz_title: "Quiz Title",
quiz_questions:
[
    {
        question_id:1,
        question_question:"The Question",
        question_choices:[
            {
                choice_id:1,
                choice_text:"The Choice Text"
            },
            {
                choice_id:2,
                choice_text:"The Choice Text"
            }]
    },
    {
        question_id:2,
        question_question:"The Question",
        question_choices:[
            {
                choice_id:1,
                choice_text:"The Choice Text"
            },
            {
                choice_id:2,
                choice_text:"The Choice Text"
            }]
    }
]
}]

Is it possible to get this kind of result by using just a single query? So far I can get a single Quiz object and get all related Questions by doing:

quiz_object.questions_set.all()

However, I can't get to the Choices level and the results are stored in different variables.

You can't do it all in one query, but you can use prefetch_related() to minimize the number of queries. In your case it might look like this, and would probably result in a total of three database queries:

Quiz.objects.filter(stuff=whatever).prefetch_related('question__choice')

Compare this example from the documentation :

Restaurant.objects.prefetch_related('pizzas__toppings')

This will prefetch all pizzas belonging to restaurants, and all toppings belonging to those pizzas. This will result in a total of 3 database queries - one for the restaurants, one for the pizzas, and one for the toppings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM