Reordering list of models in Django Admin

Wouldn’t it be great if sorting models in the Django Admin is just as easy as setting a priority number in your ModelAdmin subclass?

In my project, I made a BaseAdmin class that has an admin_priority property:

class BaseAdmin(admin.ModelAdmin):
    admin_priority = 20

This property can be overridden to a lesser number to boost a model upwards the list of models in the Django Admin site, or a greater number to push it downwards.

To make this work, I replaced the default admin.AdminSite.get_app_list with this:

def get_app_list(self, request):
    app_dict = self._build_app_dict(request)
    from django.contrib.admin.sites import site
    for app_name in app_dict.keys():
        app = app_dict[app_name]
        model_priority = {
            model['object_name']: getattr(
                site._registry[apps.get_model(app_name, model['object_name'])],
                'admin_priority',
                20
            )
            for model in app['models']
        }
        app['models'].sort(key=lambda x: model_priority[x['object_name']])
        yield app

admin.AdminSite.get_app_list = get_app_list

I wish to add this to Django itself. Is it better to contribute to the repo itself or just create my own plugin?

1 Like

Hi @clrke

This is a nice approach and not too much code - goo d work. I’ve seen a different approach setting the Meta.verbose_name attribute for all models to include a prefix to force sorting, and yours is definitely a nicer.

That said - this is a pretty small amount of code to implement it on a new project. Merging a new feature like this to Django means it needs tests, documentation, and maintenance from now until forever, so we’re always cautious about adding new things. It might be better if you release this as a third party package, or share the code in a blog post, and if you can show that it’s popular then it’d be more worth consideration of merging.

Thanks,

Adam

Thanks for the compliment and advice, @adamchainz!

I’ll write a blog post about this soon.