Annotate query set with field value

Vémundr picture Vémundr · Jul 27, 2016 · Viewed 12.5k times · Source

Multilanguage website with translations stored in columns of one table. Need to pass query set to template with already filtered translations. Language variable is stored in session.

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')

Thought would be nice just to annotate the qs with the needed text, however I failed to find how to annotate with a field value. Something like

item = Item.objects.all().annotate(text=description.klingon)

Another approach would be to use a template filter like

item.description|choose_lang:request

but sorting the qs before the template seems neater.

Answer

Cláudio Fernandes picture Cláudio Fernandes · Jul 27, 2016

You can use the F() expression here

from django.db.models import F    
item = Item.objects.all().annotate(text=F('description__klingon'))

Source