Django多语言模型/按语言过滤帖子

时间:2018-11-11 18:28:14

标签: django

这是我简单的博客模型;

class Article(models.Model):

    author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
    title_en = models.CharField(max_length = 120, verbose_name="Title_En")
    title_de = models.CharField(max_length = 120, verbose_name="Title_De")
    category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
    content_en = RichTextField(verbose_name="Content_En")
    content_de = RichTextField(verbose_name="Content_De")
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
    image = models.ImageField(blank=True, null=True, verbose_name="Add Photo (.jpg .png)")
    slug = models.SlugField(unique=True, max_length = 130)

    def __str__(self):
        return self.title

我将url用作此类语言;

domainname.com/en/ domainname.com/de /

例如,如何显示在domainname.com/de url中仅属于title_de和content_de的内容?

如何进行语言过滤?有一个简单的解决方案吗? (我使用django 2.1.2。我尝试django-modeltranslation或其他人无法使用此django版本...)

谢谢...

2 个答案:

答案 0 :(得分:1)

基于keyward参数的过滤是解决此问题的一种方法。我宁愿添加语言字段'EN'或' DE',而不是重复相同的操作标题和内容字段的种类,并基于此进行过滤。例如,

商品模型可以像

class Article(models.Model):
     LANGUAGE_TYPES = (
    ('EN', 'EN'),
    ('DE', 'DE'),
     )

    author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
    title = models.CharField(max_length = 120, verbose_name="Title")
    category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
    content = RichTextField(verbose_name="Content")
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
    image = models.ImageField(blank=True, null=True, verbose_name="Add Photo (.jpg .png)")
    slug = models.SlugField(unique=True, max_length = 130)
    language = models.CharField(
    max_length=10, choices=LANGUAGE_TYPES)

    def __str__(self):
        return self.title

我们的网址可以像

from django.urls import path

from .views import (ArticleView)

urlpatterns = [
    path('article/<slug:type>/', ArticleView.as_view(), name='article'),
]

我们的观点可能像

from rest_framework import views, status
from .serializers import ArticleSerializer
from .models import Article

class ArticleView(views.APIView):

    def get(self, request):
        article_language_type = self.kwargs.get('type', None)
        articles = Article.objects.filter(language=article_language_type)
        serializer = ArticleSerializer(articles, many=True)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

答案 1 :(得分:1)

您可以创建一个descriptor class来包装翻译后的字段,例如,

from django.utils import translation

class TranslatedField:
    def __init__(self, field_name):
         self.partial_field_name = field_name

    def __get__(self, obj, objtype):
        return getattr(obj, self.field_name)

    def __set__(self, obj, value):
        return setattr(obj, self.field_name,  value)

    @property
    def field_name(self):
        language_code = translation.get_language()
        rerurn self.partial_field_name + '_' + language_code

class Article(models.Model):

    title_en = models.CharField(max_length=120)
    title_de = models.CharField(max_length=120)
    title = Translated Field('title')

那你就可以做

article = Article.objects.create(
    title_en='In english',
    title_de='In German'
)

print(article.title)  # 'In english'
translation.set_language('de')
print(article.title)  # 'In German'
article.title = 'In German!'
print(article.title)  # 'In German!'
translation.set_language('en')
print(article.title)  # 'In english'

(未经测试,因此可能有错别字)

我会使用开箱即用的东西,例如https://github.com/deschler/django-modeltranslation