Using image.user.userprofile
does the trick. Also, get_profile()
is deprecated.
Using Django's selected_related, but still resulting in additional database hit
-
30-06-2022 - |
Question
I have a UserProfile
model with a OneToOneField
to auth.models.User
.
I also have an Image
model with a ForeignKey
to User
.
In one of my views, I get a bunch of Image
s like this:
Image.objects.select_related('user__userprofile')
and later, for each image fetched above I do:
userprofile = image.user.get_profile()
I was expecting that this would not cause another database hit, but it does. What am I doing wrong?
Please note that I think the .selecte_related()
is actually doing its job, because I can see a LEFT OUTER JOIN
in the SQL that gets executed:
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
La solution
Autres conseils
Try to use
userprofile = image.user__userprofile
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow