简体   繁体   English

相关对象上的Django多维查询集

[英]Django MultiDimensional Queryset on Related objects

I'm a Django newbie and I created a quiz application. 我是Django新手,并创建了测验应用程序。 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: 测验/ 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对象并获取所有相关问题:

quiz_object.questions_set.all()

However, I can't get to the Choices level and the results are stored in different variables. 但是,我无法进入Choices级别,结果存储在不同的变量中。

You can't do it all in one query, but you can use prefetch_related() to minimize the number of queries. 您无法在一个查询中完成所有操作,但是可以使用prefetch_related()来减少查询数量。 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. 这将导致总共3个数据库查询-一个针对餐厅,一个针对比萨饼和一个针对浇头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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