Custom models display ordering for Django admin dashboard

Posted HiroshiFuu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Custom models display ordering for Django admin dashboard相关的知识,希望对你有一定的参考价值。

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,

  1. Retrieve the original list
  2. Define the ordering for each app, as the model names are different
  3. I am using app_lable to specify which app to apply
  4. 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

以上是关于Custom models display ordering for Django admin dashboard的主要内容,如果未能解决你的问题,请参考以下文章

python blender-display-opengl-lights-on-custom-panel.py

keras inceptionV3“base_model.get_layer('custom')”错误ValueError:没有这样的层:自定义

Laravel Custom Pivot Model缺少字段

在Model-Driven App中使用自定义页面(Custom Page)

提高ValueError(“预期单例:%s”%self)ValueError:预期单例:product.pricelist()

Model.get_FOO_display() 方法在使用 values() QuerySets 时不起作用