A better way than eval() when translating keyword arguments in QuerySets (Python/Django)
I'm using django-transmeta (couldn't get anything else working better with django 1.2.5) which creates several columns in a table like: content_en, content_es, content_it
Before implementing i18n I had:
items = Items.objects.filter(categories__slug=slug)
now category.slug is internationalized therefore I have "category.slug_en", "category.slug_es", "category.slug_it" and so on.
So I though of doing:
from django.db.models import Q
from 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),
}
i开发者_运维问答tems = Items.objects.filter(queryset[current_lang])
But if I do it this way whenever I'll need to add a new language I'll have to change the code and of course I don't want to do that.
So I did:
from django.db.models import Q
from 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 this case I'm using eval() which of course is synonymous with evil() and would be better to avoid it.
So I was wondering: is there a better way to do this?
Thanks a lot!
Try
q = Q(**{"categories__slug_" + current_lang + "__contains": slug})
items = Items.objects.filter(q)
精彩评论