Django

Code

Ticket #4196 (reopened)

Opened 3 years ago

Last modified 1 year ago

[patch] Use select_related() when retrieving a user profile

Reported by: Matt Riggott Assigned to: nobody
Milestone: Component: Contrib apps
Version: SVN Keywords:
Cc: Triage Stage: Design decision needed
Has patch: 1 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

Description

To start with an example:

>>> from django.contrib.auth.models import User
>>> u = User.objects.get(pk=1)
>>> p = u.get_profile()
>>> p.user.username
'dave'
>>> from django.db import connection
>>> len(connection.queries)
3

Even though I'm dealing with two database objects (a User and its profile) three queries were executed. The first to get the user, the second to get the profile, and the third to get the user again.

If line 257 in django/contrib/auth/models.py was changed to use select_related the database would only be hit twice.

It's a minor thing, but I thought I'd mention it. You know, just in case you guys ran out of patches to test and such.

(If a user profile has lots of foreign key fields this could result in a lot of objects being created, which is why I've limited the depth to 1.)

Attachments

user_get_profile.diff (0.7 kB) - added by Matt Riggott on 05/01/07 12:18:40.

Change History

05/01/07 12:18:40 changed by Matt Riggott

  • attachment user_get_profile.diff added.

05/01/07 21:25:04 changed by Gary Wilson <gary.wilson@gmail.com>

  • needs_better_patch changed.
  • stage changed from Unreviewed to Design decision needed.
  • needs_tests changed.
  • needs_docs changed.

Yeah I'm not sure what would be best here. The larger query using select_related() may be the same or worse than the one additional query that would be saved (especially with several foreign keys in the user profile).

08/07/07 17:59:04 changed by davep@atomicdroplet.com

Just to add my ill-informed opinion as a Django newbie - I arrived here while googling trying to find out how to apply select_related to get_profile. Obviously you don't, yet. Is there anything wrong with adding a default flag ... get_profile(related=true) ... type thing?

09/14/07 12:53:56 changed by PhiR

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

This is really a very minor implementation issue.

03/13/09 08:26:50 changed by anonymous

  • status changed from closed to reopened.
  • resolution deleted.

Is it possible to have a get_profile(related=True) sort of implementation wherein based on the value of related, we can have get_profile getting either select_related or not? I understand is was closed as very minor, but this does help quite a bit and I do not want to change the django code in my system for this. The problem is that when a new version comes, we have to remember putting it again.


Add/Change #4196 ([patch] Use select_related() when retrieving a user profile)




Change Properties
Action