13

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.

Vémundr
  • 395
  • 1
  • 7
  • 17

1 Answers1

22

You can use the F() expression here

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

Source

Artem Bernatskyi
  • 4,185
  • 2
  • 26
  • 35
  • Thank you. I tried these F things by myself, but It turned out that I made a mistake in a different place of the code and when it failed I figured that I had this F instructions wrong :) Now all works fine. – Vémundr Jul 27 '16 at 14:08
  • con I also get all fields from the Localization model using F instead of writing all the fields one by one ?? – Adarsh Srivastav Mar 02 '22 at 07:51
  • Query could do without calling `all()`, therefore becoming: `Item.objects.annotate(text=F('description__klingon'))` – Niccolò Mineo Apr 18 '23 at 14:31