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 Images 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
Was it helpful?

Solution

Using image.user.userprofile does the trick. Also, get_profile() is deprecated.

OTHER TIPS

Try to use

userprofile = image.user__userprofile
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top