Custom models display ordering for Django admin dashboard

2756 단어
Django Admin
By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order.
https://docs.djangoproject.co...
    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        app_dict = self._build_app_dict(request)

        # Sort the apps alphabetically.
        app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

        return app_list

https://github.com/django/dja...
There are multiple ways to achieve this on the internet
  • Adding a numeric prefix for each verbose_name_plural in App Model Meta
  • Override admin/base.html tempalte
  • Override AdminSite class and get_app_list() method

  • For this article, I will be using a way that to override the get_app_list class method only without overriding the class.
    How to do it?
    Define the class method normally.
    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        # Retrieve the original list
        app_dict = self._build_app_dict(request)
        app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
    
        # Sort the models customably within each app.
        for app in app_list:
            if app['app_label'] == 'auth':
                ordering = {
                    'Users': 1,
                    'Groups': 2
                }
                app['models'].sort(key=lambda x: ordering[x['name']])
    
        return app_list

    Some things to take note,
  • Retrieve the original list
  • Define the ordering for each app, as the model names are different
  • I am using app_lable to specify which app to apply
  • The medel name is verbose_name_plural or verbose_name

  • Then update the method with custom method
    admin.AdminSite.get_app_list = get_app_list

    좋은 웹페이지 즐겨찾기