如何在django-admin中按多个字段订购?
由于
答案 0 :(得分:12)
试试这个:
在模型Meta
中设置排序:
class Meta:
ordering = ["some_field", "other_field"]
并在admin.py
中添加此类:
from django.contrib.admin.views.main import ChangeList
class SpecialOrderingChangeList(ChangeList):
"""
Django 1.3 ordering problem workaround
from 1.4 it's enough to use `ordering` variable
"""
def get_query_set(self):
queryset = super(SpecialOrderingChangeList, self).get_query_set()
return queryset.order_by(*self.model._meta.ordering)
在admin.ModelAdmin
def get_changelist(self, request, **kwargs):
return SpecialOrderingChangeList
来源:https://groups.google.com/forum/?fromgroups#!topic/django-users/PvjClVVgD-s
答案 1 :(得分:3)
直到django 1.4(目前处于alpha版)django管理员只按Meta ordering
中的第一列排序。您可以通过覆盖查询集来解决此问题:
class MyAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(MyAdmin, self).queryset(request)
qs = qs.order_by('last_name', 'first_name')
return qs
答案 2 :(得分:1)
继上述user535010的回复: 我挣扎是因为在添加建议的代码后,我再也无法通过点击管理列表视图中的标题来订购字段。我修改了为MyModelAdmin建议的get_changelist方法,如下所示:
def get_changelist(self, request, **kwargs): #ordering issue in 1.3 workaround
try:
if not request.GET['o']:
return SpecialOrderingChangeList
except KeyError:
pass
return super(MyModelAdmin, self).get_changelist(request)
答案 3 :(得分:0)
使用多列排序修复进行点击排序所需的功能如下:
def get_changelist(self, request, **kwargs):
try:
if request.GET['o']:
return super(ModelAdmin, self).get_changelist(request)
except KeyError:
pass
return SpecialOrderingChangeList
以其他方式回答jenniwren的回答: - )
答案 4 :(得分:0)
Django模型管理员支持在Django 2.0+中按多个值进行排序。您现在可以像这样使用它:
class MyAdmin(admin.ModelAdmin):
ordering = ['last_name', 'first_name']