How to speed up Django Admin: Foreignkey and ManyToManyField

If you have a Foreignkey or ManyToManyField in your admin form, but you don’t need to change it in any way, replace it with a label. Say, you have a model:

class Student(models.Model):
    ...
    class_obj = models.ForeignKey('Class', on_delete=models.CASCADE)

And in your Django Admin you want to have thic field:

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    fields = ('class_obj',)

There is no problem if you have, say, 10-100 Class instances, but if you have thousands of them – the interface would take a lot of time to load.

Instead of that, make a label property and replace the original field with it.

class Student(models.Model):
    ...
    class_obj = models.ForeignKey('Class', on_delete=models.CASCADE)

    @property
    def class_obj_str(self):
        return self.class.name

And then in the ModelAdmin:

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    readonly_fields = ('class_str',)
    fields = ('class_obj_str',)