我有一個UserProfile
模型與OneToOneField
到auth.models.User
。 我也有一個Image
模型與ForeignKey
到User
。使用Django的selected_related,但仍然導致額外的數據庫命中
在我的觀點之一,我得到了一堆Image
就像這樣:
Image.objects.select_related('user__userprofile')
後來,上面我拿來每個圖像做:
userprofile = image.user.get_profile()
我期待這不會導致另一個數據庫命中,但它確實如此。我究竟做錯了什麼?
請注意,我覺得.selecte_related()
其實就是做自己的工作,因爲我可以看到在被執行的SQL一個LEFT OUTER JOIN
:
SELECT * FROM "myapp_image"
INNER JOIN "auth_user" ON ("myapp_image"."user_id" = "auth_user"."id")
LEFT OUTER JOIN "myapp_userprofile" ON (
"auth_user"."id" = "myapp_userprofile"."user_id")
ORDER BY "myapp_image"."uploaded" DESC, "myapp_image"."id" DESC
LIMIT 64
你就近了。 'image.user.userprofile'做到了。謝謝! –
感嘆,image.user__userprofile應該是模板的代碼。我還在睡覺... – Simon