我正在构建自己的自定义管理器以获取模型的翻译。想法是:
主要模式:
class BlogTranslationManager(models.Manager):
def language(self):
lang = translation.get_language()
return BlogTranslation.objects.filter(lang=lang)
class ArticleTranslationManager(models.Manager):
def language(self):
lang = translation.get_language()
return ArticleTranslation.objects.filter(lang=lang)
class Blog(models.Model):
created = models.DateTimeField()
objects = models.Manager()
translations = BlogTranslationManager()
# PROBLEM HERE
@property
def articles(self):
# here I need translations of all articles of this blog
# I cannot do:
return self.blog_articles.translations.language('en')
# because 'translations' Manager cannot be called on QuerySet
# what can I do here? am I missing something in CustomManagers?
class Article(models.Model):
blog = models.ForeignKey(Blog, related_name="blog_articles")
objects = models.Manager()
translations = ArticleTranslationManager()
class BlogTranslation(models.Model):
book = models.ForeignKey(Book, related_name="book_translations")
field_name = models.CharField(max_length=10)
lang = models.CharField(max_length=3)
translation = models.TextField()
class ArticleTranslation(models.Model):
article = models.ForeignKey(Article, related_name="article_translations")
field_name = models.CharField(max_length=10)
lang = models.CharField(max_length=3)
translation = models.TextField()
在模板中,我希望能够致电:
{{ blog.articles }}
我在上面的代码中描述了问题,有关它的任何想法?任何帮助都非常感谢!
答案 0 :(得分:1)
首先尝试使用Article.translations
管理器,然后过滤生成的查询集。如果我正确理解你的模型,你需要这样的东西:
@property
def articles(self):
return Article.translations.language('en').filter(article__blog=self)