使用字段值注释查询集

Vém*_*ndr 6 django multilingual annotate

多语言网站,翻译存储在一个表的列中.需要将查询集传递给已经过滤过的翻译的模板.语言变量存储在会话中.

class Item(models.Model):
    name = models.CharField(max_length=128)
    description = models.ForeignKey(Localization)

class Localization(models.Model):
    klingon = models.TextField(blank=True, null=True, verbose_name='klingon')
    english = models.TextField(blank=True, null=True, verbose_name='english')
Run Code Online (Sandbox Code Playgroud)

想到用所需文本注释qs会很好,但是我没有找到如何使用字段值进行注释.就像是

item = Item.objects.all().annotate(text=description.klingon)
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用模板过滤器

item.description|choose_lang:request
Run Code Online (Sandbox Code Playgroud)

但在模板之前排序qs似乎更整洁.

小智 10

您可以在此处使用F()表达式.

from django.db.models import F    
item = Item.objects.all().annotate(text=F('description__klingon'))
Run Code Online (Sandbox Code Playgroud)

文件:https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations