On Mon, 2009-08-03 at 02:48 -0700, alant...@neei.uevora.pt wrote:
> Hello,
> 
> I'm displaying lot of user profile picture with are on a user profile
> (i'm using contrib.auth). So for each picture I have a query for the
> user profile.
> 
> I wanted to use User.objects.filter(stuff).select_related
> ('userprofile') but this has no effect. Any ideas how to prevent the
> +200 queries from happening?

The link between the two models runs from UserProfile -> User, not the
other way around. The select_related() call only follows forwards links,
so it will not traverse from User to UserProfile. It's not completely
trivial to add backwards-link following, particularly because there can
be multiple values for backwards links.

However, you can often turn this type of query around. Instead of
filtering User objects, filter Userprofile objects, where you can use
select_related(). Thus

        User.objects.filter(username="fred")
        
becomes

        UserProfile.objects.filter(user__username="fred").select_related()
        
The main trick here is that each condition needs the "user__" bit
prepended, so a little munging of filters -- either automatically or by
hand -- is required. You can still access the User instance attributes
via

        obj.user.username
        
where "obj" is now a UserProfile instance.

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to