5

In Django, on a recommended setup, a UserProfile instance is linked by a OneToOneField with its User instance.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    data = ...

What is the most efficient way inside a view for retrieving both, user and profile? Can I do a select_related() inner join query, to get both objects with one database hit? Or does it always come down to two separate calls? Possibly, Django's auth middleware retrieves the user instance even before the view is called ... does anybody know?

Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97
  • 1
    To provide more details: The profile can be retrieved via request.user.userprofile or request.user.get_profile(). However, both result in two database hits. My question is: can we reduce this to only one inner join query using select_related ... and if so: is this more efficient than the "usual" way? – Simon Steinberger Jul 15 '12 at 18:32

1 Answers1

1

The user profile can be retrieved using get_profile().

See documentation: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

Köver
  • 371
  • 4
  • 12
  • 1
    Django mentions somewhere, that get_profile caches its result, but that's true for all such requests. So I really don't see the advantage when compared to "user.userprofile". But what really baffles me, is that when using both, user.get_profile and user.userprofile, in teh same template, the database gets hit twice. So up to now, I consistently stick with user.userprofile. Aynway, both methods of retrieving the profile result in 2 database hits: 1x user + 1x profile. A select_related call does that in ONE inner join. Is that possible and advantageous? – Simon Steinberger Jul 15 '12 at 18:29