2

I'm getting thousands of these queries when I try to open up a model in the Django admin interface and it's leading to a serious performance issue.

[sql] SELECT ... FROM `auth_user` WHERE `auth_user`.`id` = 9535
[sql] (21ms) Found 1 matching rows
[sql] SELECT ... FROM `auth_user` WHERE `auth_user`.`id` = 9536
[sql] (20ms) Found 1 matching rows

Any ideas why Django admin isn't using select_related()?

Here are (I think) the relevant parts of the model (I'm looking at an instance of the Student model in the admin):

from django.contrib.auth.models import User

class Student(models.Model):
    user = models.OneToOneField(User, unique=True)
    mhtl_user = models.OneToOneField(MHTLUser, unique=True)
    def __str__(self):
        return u"%s %s" % (self.user.first_name, self.user.last_name)

class MHTLUser(models.Model):
    user = models.OneToOneField(User, unique=True)
    def __str__(self):
        return str(self.user)
jpic
  • 32,891
  • 5
  • 112
  • 113
Charles Offenbacher
  • 3,094
  • 3
  • 31
  • 38
  • Still experimenting -- just discovered if I comment out "mhtl_user = models.OneToOneField(MHTLUser, unique=True)" the queries go away. So it's related to that somehow... – Charles Offenbacher Mar 15 '12 at 12:35
  • Aaand it's the __str__ function in MHTLUser. If that is gone, problem solved. But I'm still curious why that's an issue though. – Charles Offenbacher Mar 15 '12 at 12:37
  • What are you using to show the SQL queries like this ? – Kedare Mar 15 '12 at 19:11
  • 1
    https://github.com/dcramer/django-devserver =) – Charles Offenbacher Mar 15 '12 at 22:13
  • Not directly related to your problem but can I ask you why you define `__str__` instead of `__unicode__`? Not mentioning that your `Student ` `__str__` return unicode... – Etienne Mar 16 '12 at 01:57
  • Short answer is that I don't really understand character encodings, or how Python deals with them, and I think there was some issue with "ordinal not in range" with ascii where __str__ was being called. Rather than change the library that called __str__, it seemed easier to just return unicode. Lol, that's probably terrible, and thanks for making me realize I should probably learn these things. – Charles Offenbacher Mar 16 '12 at 12:30

2 Answers2

3

Or just enable list_select_related.

class MyModelAdmin(admin.ModelAdmin):
    list_select_related = True
    # ....
jpic
  • 32,891
  • 5
  • 112
  • 113
  • I originally accepted this answer because I thought it worked, but it was actually another change that fixed it, not this. I had commented the __str__ method in MHTLUser. Using this ModelAdmin doesn't actually help in this case. – Charles Offenbacher Mar 16 '12 at 00:10
2

You could make Django use select_related by defining your own ModelAdmin like this

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.select_related()
Juho
  • 983
  • 5
  • 9