我有像这样定义的模型
class Foo(Model):
id = AutoField(primary_key = True)
code = CharField(blank = False, unique = False, max_length = 64)
class FooName(Model):
id = AutoField(primary_key = True)
foo = ForeignKey(Foo, blank = False, related_name = '+')
language = CharField(blank = False, max_length = 16)
value = CharField(blank = False, max_length = 256)
class Bar(Model):
id = AutoField(primary_key = True)
foo = ForeignKey(Foo, blank = False, related_name = '+')
所以,对于像' 我有'fooname'表格,如 当然,我已经请求.LANGUAGE设置为有意义的东西。 问题是:如何在Foo模型上将name属性动态评估为本地化名称,即 但没有明确传递请求对象? 我的意思是,如果我有Bar的集合,我想写一些类似 没有复杂的语言匹配(对'en-US'使用'en')或回退(如果没有当前语言的值,则使用'en-US')逻辑。{ 1, 'apple' },
{ 1, 'pear' }
{ 1, 1, 'en', 'Apple'},
{ 2, 1, 'fr', 'Pomme'},
{ 3, 2, 'en', 'Pear'},
{ 4, 2, 'fr', 'Poire'}
self.name = FooName.objects.get(foo = self, language = request.LANGUAGE)
for bar in Bar.objects.filter(...):
fn = bar.foo.name
答案 0 :(得分:0)
你为什么不能这样做?
for bar in Bar.objects.filter(...):
fn = FooName.objects.get(foo=bar.foo, language=request.LANGUAGE).value
答案 1 :(得分:0)
如果要在模板中执行此操作,则需要自定义模板标记。在此,您可以访问请求对象。您可以提取语言并将其传递给模型实例方法。
# models.py
from django.db import models
class Foo(models.Model):
code = models.CharField(blank=False, max_length=64)
def get_name(self, language_code):
return self.foo_set.filter(language=language).get()
class FooName(Model):
foo = models.ForeignKey(Foo)
language = models.CharField(max_length=16)
value = models.CharField(max_length=255)
# templatetages/mytags.py
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def resolve_foo_name(context, foo_object):
return foo_object.get_name(context.LANGUAGE)
# template.html
{% load mytags %}
{% resolve_foo_name foo_object %}