是否可以使用主动语言订购Django模型?

时间:2013-04-18 14:50:31

标签: python django django-models internationalization

我正在研究Django 1.5.1并且我想知道以下问题:是否可以使用django-transmeta并使用用户访问的活动语言在可翻译字段中定义模型中的排序管理员?

到目前为止,我实现了使用已翻译的字段并使用默认语言而不是活动语言进行排序,因为对get_language()的调用始终返回settings.py中定义的默认语言,如果我调用Meta类(或来自ModelAdmin类)的方法。

以下是我正在处理的代码,感谢您的帮助:

class StartupType(models.Model):

    __metaclass__ = TransMeta

    name = models.CharField(_("Name"), max_length=30, unique=True)
    slug = models.SlugField(_("Slug"), max_length=30, unique=True, editable=False)

    class Meta:

        verbose_name = _("Startup type")
        verbose_name_plural = _("Startup types")
        translate = (
            "name",
        )
        ordering = [
            "name_" + LANGUAGE_CODE,
        ]

1 个答案:

答案 0 :(得分:1)

根据documentation,您可以定义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

如果您仍然没有使用正确的语言,请确保在settings.py中添加了之后的区域设置中间件,例如:

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公开为动态属性。