根据文档,您可以定义一种get_ordering()
使用动态订单的方法:
# admin.py
from django.contrib import admin
from .models import StartupType
class StartupTypeAdmin(admin.ModelAdmin):
def get_ordering(self, request):
language_code = request.LANGUAGE_CODE[:2]
return ('name_%s' % language_code,)
admin.site.register(StartupType, StartupTypeAdmin)
这也适用于使用get_language()
而不是request.LANGUAGE_CODE
.
如果您仍然没有获得正确的语言,请确保您在 Session 中间件之后settings.py
添加了 Locale 中间件,例如:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
编辑:添加了在模型上定义动态排序的替代方法。
如果您还想设置ordering
模型类,似乎有点复杂,这是我能想到的最好的:
from django.db import models
from django.db.models.options import Options
from django.utils.translation import get_language
from django.utils.translation import ugettext_lazy as _
from transmeta import TransMeta, get_real_fieldname
class TranslatedOptions(Options):
@property
def ordering(self):
lang = get_language()[:2]
return [get_real_fieldname(f, lang) for f in self.orig_ordering]
@ordering.setter
def ordering(self, value):
self.orig_ordering = value
class TransMetaOrdering(TransMeta):
def __new__(cls, name, bases, attrs):
new_class = super(TransMetaOrdering, cls).__new__(cls, name, bases, attrs)
options = TranslatedOptions(None)
for k, v in new_class._meta.__dict__.iteritems():
setattr(options, k, v)
new_class._meta = options
return new_class
class StartupType(models.Model):
__metaclass__ = TransMetaOrdering
name = models.CharField(_("Name"), max_length=30)
slug = models.SlugField(_("Slug"), max_length=30, editable=False)
class Meta:
verbose_name = _("Startup type")
verbose_name_plural = _("Startup types")
translate = (
"name",
)
ordering = (
"name",
)
这将用一个类型的新对象替换StartupType._meta
(类型的对象),该对象将作为动态属性公开。django.db.models.options.Options
TranslatedOptions
ordering