django默认管理admin对象对模型的排序⾃定义django2/3中,默认的模型管理中,模型的排序是名称的字母顺序,源代码位置:.venv/python3.6/site-
packages/django/contrib/admin/sites.py中AdminSite
1def get_app_list(self, request):
2"""
3 Return a sorted list of all the installed apps that have been
4 registered in this site.
5"""
6 app_dict = self._build_app_dict(request)
7
8# Sort the apps alphabetically.
9 app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
10
11# Sort the models alphabetically within each app.
12for app in app_list:
13app['models'].sort(key=lambda x: x['name'])
14
15return app_list
16
17 @never_cache
18def index(self, request, extra_context=None):
19"""
20 Display the main admin index page, which lists all of the installed
21 apps that have been registered in this site.
22"""
23 app_list = _app_list(request)
django admin 自定义页面24
25 context = {
26 **self.each_context(request),
27'title': self.index_title,
28'app_list': app_list,
29 **(extra_context or {}),
30 }
31
32 request.current_app = self.name
33
34return TemplateResponse(request, self.index_template or'admin/index.html', context)
以上为django中的源代码,可以看到
app['models'].sort(key=lambda x: x['name'])为实际的排序算法。
⾸先参考官⽅⽂档覆盖 Django Admin 的AdminSite类:
实际的处理⽅法有以下三种:但本⼈推荐和采⽤的是第三种
在每个 APP model ⾥为 Meta 类下的verbose_name_plural字段添加数字前缀
重写admin/base.html模板页⾯
重写AdminSite类的index()⽅法
1、在项⽬的根⽬录下到项⽬同名⽂件夹,⽐如:项⽬名称为myproject,则在它下⾯的myproject⽂件下新建admin.py 在其中创建⼀个类覆盖默认的管理类:
ib.admin import AdminSite
class ModelIndexReOrder(AdminSite):
def get_app_list(self, request):
"""
Return a sorted list of all the installed apps that have been
registered in this site.
"""
re_order = {
'Company': 101,
'Staff': 102,
'Customer': 201,
'User': 202,
}
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排序,默认的不排序
if app["app_label"] == 'APP名称':
app['models'].sort(key=lambda x: re_order[x['object_name']]) else:
app['models'].sort(key=lambda x: x['name'])
return app_list
2、在同样的⽬录下创建apps.py
ib.admin.apps import AdminConfig
#类名随便,可⾃⼰辨认就⾏
class APPNameModelsConfig(AdminConfig):
default_site = '项⽬名称(这⾥就是myproject).admin.ModelIndexReOrder' 3、修改项⽬默认配置settings中
INSTALLED_APPS = [
# 'ib.admin',
'crm.apps.APPNameModelsConfig',
......
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论