[Django]-Running n time django_content_type query

4👍

Import UserChangeForm from django.contrib.auth.forms and add form = UserChangeForm to your UserAdmin(admin.ModelAdmin) class.

It adds this line: user_permissions.queryset = user_permissions.queryset.select_related('content_type') which replaces all the n queries with one single query.

Depending on your user model, you may need to extend UserChangeForm (see docs).

1👍

The problem appears when you are subclussing AbstractUser in your user model.
Shortly: you must change your change form in django admin.
Firslty create your new change form and set model = User, where User is your new user model subclassed from AbstractUser:

class AdminChangeForm(forms.UserChangeForm):
    class Meta:
        model = User
        fields = '__all__'

Then set form in your user admin to class above:

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ['id', 'username', 'first_name', 'last_name', 'email', 'is_active', 'last_login', 'date_joined']
    list_filter = ('last_login', 'date_joined', 'is_active')
    form = AdminChangeForm

Full tutorial:
https://testdriven.io/blog/django-custom-user-model/

1👍

I have same problem. add this function in your UserAdmin

from django.contrib import admin
from django.contrib.auth.models import Permission
from foo.models import UserModel # your auth model

@admin.register(UserModel)
class UserAdmin(admin.ModelAdmin):
   def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == 'user_permissions':
        kwargs['queryset'] = Permission.objects.all().select_related('content_type')
    return super(UserAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

above code override Permission queryset to reduse queries by select_related function

👤Radesh

Leave a comment