Django

Code

Ticket #8660 (closed: fixed)

Opened 3 months ago

Last modified 2 months ago

Calling User.get_profile() should pre-populate the user foreign key on the profile object

Reported by: mmalone Assigned to: nobody
Milestone: post-1.0 Component: Authentication
Version: SVN Keywords: cache profile user auth
Cc: Triage Stage: Accepted
Has patch: 0 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

Description (Last modified by mtredinnick)

When you use the User.get_profile() method to fetch a profile object, it doesn't pre-populate profile's user attribute. This results in unnecessary DB queries when you go from User -> UserProfile and then later go from UserProfile -> User. This is actually a fairly common use case because people tend to attach methods that "extend" the user object in UserProfile?, since they can't directly extend User.

For example, if you create a full_name() method on UserProfile that returns '%s %s' % (self.user.first_name, self.user.last_name), then in your templates, you do {{ User.get_profile.full_name }} , you end up doing two DB queries when only one in necessary.

The solution seems simple enough since the profile's User object must be called user. In django/contrib/auth/models.py a one liner after fetching the profile should do the trick:

  self._profile_cache = model._default_manager.get(user__id__exact=self.id)
+ self._profile_cache.user = self

Attachments

Change History

08/28/08 17:50:39 changed by mtredinnick

  • needs_better_patch changed.
  • stage changed from Unreviewed to Accepted.
  • needs_tests changed.
  • needs_docs changed.

(The reason this isn't a real patch is because mmalone was working off a non-trunk checkout for his commercial stuff. So I asked him just to file the right line and we can turn it into a trivial patch later. Just noting so nobody wonders why he's being a bad patch writer.)

08/28/08 17:52:22 changed by mtredinnick

  • description changed.

10/05/08 07:07:51 changed by mtredinnick

Fixed in r9152.

10/05/08 07:08:01 changed by mtredinnick

  • status changed from new to closed.
  • resolution set to fixed.

Add/Change #8660 (Calling User.get_profile() should pre-populate the user foreign key on the profile object)




Change Properties
Action