gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:02:41 25 4
gpt4 key购买 nike

有我的简单博客模型;

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/域名.com/de/

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

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

谢谢...

最佳答案

您可以创建一个 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

关于Django 多语言模型/按语言过滤帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53251845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com