我在Django中建立了一个复杂的数据库模型,我必须根据过滤器数据做一些计算。我有一个Test
对象,一个TestAttempt
对象和一个UserProfile
对象(外键返回测试,外键返回给用户配置文件)。我在TestAttempt
上运行了一个方法,该方法计算测试分数(根据用户提供的选项数量与与每个测试相关的正确答案进行比较)。然后我在Test
上运行另一种方法,该方法根据每个关联的TestAttempt
的平均测试分数计算平均测试分数。但有时我只想要基于与特定集关联的关联TestAttempt
的供应子集的平均值的UserProfiles
。因此,不要像这样计算特定测试的平均测试分数:查询查询的Django __in查询效率
[x.score() for x in self.test_attempts.all()]
然后对这些值进行平均。 我做了这样的查询:
[x.score() for x in self.test_attempts.filter(profile__id__in=user_id_list).all()]
其中user_id_list
为用户配置ID对,我想找到一个列表的形式平均测试成绩的特定子集。我的问题是:如果user_id_list
确实是整套UserProfile
的(因此过滤器将返回与self.test_attempts.all()
相同的值),并且大多数情况下都是这样,是否支付检查此案件的费用,如果是这样根本不执行过滤器?或者__in查找效率足够高,即使user_id_list
包含所有用户,运行过滤器效率也会更高。另外,我是否需要担心产生test_attempts distinct()?或者他们不可能用我的queryset的结构变成重复的?
编辑:任何人谁的兴趣看原始的SQL查询,它看起来像这样不使用滤镜:
SELECT "mc_grades_testattempt"."id", "mc_grades_testattempt"."date",
"mc_grades_testattempt"."test_id", "mc_grades_testattempt"."student_id" FROM
"mc_grades_testattempt" WHERE "mc_grades_testattempt"."test_id" = 1
,这与过滤器:
SELECT "mc_grades_testattempt"."id", "mc_grades_testattempt"."date",
"mc_grades_testattempt"."test_id", "mc_grades_testattempt"."student_id" FROM
"mc_grades_testattempt" INNER JOIN "mc_grades_userprofile" ON
("mc_grades_testattempt"."student_id" = "mc_grades_userprofile"."id") WHERE
("mc_grades_testattempt"."test_id" = 1 AND "mc_grades_userprofile"."user_id" IN (1, 2, 3))
请注意,数组(1,2,3)只是一个例子
这两种情况下生成的SQL是什么? – 2012-01-12 03:28:17
不知道,我将如何输出特定查询集的SQL?编辑,找出它。给我一点时间找到它 – ecbtln 2012-01-12 03:33:15
SQL查询已被添加 – ecbtln 2012-01-12 03:41:16