我有这样定义的模型
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 = '+')
所以,对于 'foo' 表
{ 1, 'apple' },
{ 1, 'pear' }
我有'fooname'表
{ 1, 1, 'en', 'Apple'},
{ 2, 1, 'fr', 'Pomme'},
{ 3, 2, 'en', 'Pear'},
{ 4, 2, 'fr', 'Poire'}
而且,我当然将 request.LANGUAGE 设置为有意义的东西。
问题是:如何将 Foo 模型上的 name 属性动态评估为本地化名称,即类似
self.name = FooName.objects.get(foo = self, language = request.LANGUAGE)
但没有明确传递请求对象?
我的意思是,如果我有 Bar 的集合,我想写一些类似的东西
for bar in Bar.objects.filter(...):
fn = bar.foo.name
不需要复杂的语言匹配(使用 'en' 表示 'en-US')或回退(如果当前语言没有值,则使用 'en-US')逻辑。