[Answered ]-Django admin prefetch content_type model

1👍

In your UserAdmin class, add a UserCreationForm for your User model.
Like,

from django.contrib.auth.admin import (
    UserAdmin as BaseUserAdmin, UserChangeForm as BaseUserChangeForm,
    UserCreationForm as BaseUserCreationForm
)

class UserChangeForm(BaseUserChangeForm):
    class Meta:
        model = User
        fields = '__all__'

    def clean_email(self):
        data = self.cleaned_data.get('email')
        return data.lower()

class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    ... other fields...

This should fix your query problem.

Actual part that fixes the problem:

In the default UserChangeForm, inside the __init__ method, the user_permissions queryset is being initilised with select_related optimization.

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField(
        label=_("Password"),
        help_text=_(
          "Raw passwords are not stored, so there is no way to see this "
          "user’s password, but you can change the password using "
          '<a href="{}">this form</a>.'
        ),
    )

    class Meta:
        model = User
        fields = "__all__"
        field_classes = {"username": UsernameField}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        password = self.fields.get("password")
        if password:
            password.help_text = password.help_text.format("../password/")
        user_permissions = self.fields.get("user_permissions")
        if user_permissions:
            user_permissions.queryset = 
              user_permissions.queryset.select_related(
              "content_type"
            )

Leave a comment