Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate query set with field value

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.

like image 600
Vémundr Avatar asked Jul 27 '16 13:07

Vémundr


1 Answers

You can use the F() expression here

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

Source

like image 108
Cláudio Fernandes Avatar answered Sep 18 '22 15:09

Cláudio Fernandes