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',)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.