A better way than eval() when translating keyword arguments in QuerySets (Python/Django)

你离开我真会死。 提交于 2019-12-10 16:39:18

问题


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),
}

items = 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!


回答1:


Try

q = Q(**{"categories__slug_" + current_lang + "__contains": slug})
items = Items.objects.filter(q)


来源:https://stackoverflow.com/questions/5092336/a-better-way-than-eval-when-translating-keyword-arguments-in-querysets-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!