I'm running into the fairly common issue that the django admin inline does a whole bunch of unnecessary queries to populate the dropdown. There are 4 models - when I view the user, I would like to see UserClientRoles associated with that user, displayed with the ClientRole name and the Client. When I just use the role name, it queries once for each UserClientRole (if there 3 assignments, it queries 3 times). If I include the client name, it queries every client name once for every UserClientRole.
I've tried the solution outlined here (Django admin inline: select_related), but no dice. It doesn't modify the behavior. I've also tried overriding the get_queryset method on the UserAdmin class to no effect. Nothing I've tried reduces the number of queries. I've deleted some model details for conciseness.
Here's the models:
class User(models.Model):
id = models.AutoField(primary_key=True)
email = models.CharField(unique=True, max_length=200)
class Client(models.Model):
id = models.AutoField(primary_key=True)
client_name = models.CharField(unique=True, max_length=200)
client_identifier = models.CharField(unique=True, max_length=200)
class ClientRole(models.Model):
client_role_id = models.AutoField(primary_key=True)
role_name = models.CharField(unique=True, max_length=200)
client = models.ForeignKey(Client)
def __unicode__(self):
return self.role_name + self.client_id.client_name
class UserClientRole(models.Model):
user_client_role_id = models.AutoField(primary_key=True)
client_role = models.ForeignKey(ClientRole)
user = models.ForeignKey(User)
And here are the admin models:
class UserClientRoleFormset(forms.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(UserClientRoleFormset, self).__init__(*args, **kwargs)
self.queryset = self.queryset.prefetch_related("client_role__client")
class UserClientRoleInline(admin.TabularInline):
model = UserClientRole
extra = 1
formset = UserClientRoleFormset
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
inlines = (UserClientRoleInline,)
Any clue what I'm missing?