我在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