Skip to main content
 首页 » 编程设计

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

2025年05月04日35lovecherry

我是 Django 新手,我创建了一个测验应用程序。我想知道是否可以只执行一个查询并为三个相关表获取一个多级查询集。

测验有多个问题,一个问题有多个选择。

测验/模型.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() 

我期待的结果是这样的:

[{ 
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" 
            }] 
    } 
] 
}] 

是否可以只使用一次查询就得到这种结果? 到目前为止,我可以获得一个 Quiz 对象并通过以下方式获得所有相关问题:

quiz_object.questions_set.all() 

但是,我无法进入选择级别,结果存储在不同的变量中。

请您参考如下方法:

您无法在一次查询中完成所有操作,但您可以使用 prefetch_related() 来最大程度地减少查询次数。在您的情况下,它可能看起来像这样,并且可能会导致总共三个数据库查询:

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

比较 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.