A better way than eval() when translating keyword arguments in QuerySets (Python/Django) -
i'm using django-transmeta (couldn't else working better django 1.2.5) creates several columns in table like: content_en, content_es, content_it
before implementing i18n had:
items = items.objects.filter(categories__slug=slug)
now category.slug internationalized therefore have "category.slug_en", "category.slug_es", "category.slug_it" , on.
so though of doing:
from django.db.models import q django.utils.translation import get_language current_lang = get_language() queryset = { 'en': q(categories__slug_en__contains=slug), 'es': q(categories__slug_es__contains=slug), 'it': q(categories__slug_it__contains=slug), } items = items.objects.filter(queryset[current_lang])
but if way whenever i'll need add new language i'll have change code , of course don't want that.
so did:
from django.db.models import q django.utils.translation import get_language current_lang = get_language() var = 'q(categories__slug_%s=slug)' % current_lang queryset = eval(var) items = items.objects.filter(queryset)
but in case i'm using eval() of course synonymous evil() , better avoid it.
so wondering: there better way this?
thanks lot!
try
q = q(**{"categories__slug_" + current_lang + "__contains": slug}) items = items.objects.filter(q)
Comments
Post a Comment