在查询集中翻译关键字参数时比 eval() 更好的方法 (Python/Django)
我正在使用 django-transmeta (无法让其他任何东西更好地与 django 1.2.5 配合使用),它在表中创建了多个列,例如: content_en、content_es、content_it
在实现 i18n 之前,我有:
items = Items.objects.filter(categories__slug=slug)
现在category.slug 已国际化,因此我有“category.slug_en”、“category.slug_es”、“category.slug_it”等。
所以我想这样做:
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])
但是如果我这样做,每当我需要添加一种新语言时,我就必须更改代码,当然我不想这样做。
所以我这样做了:
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)
但在这种情况下,我使用的是 eval() ,它当然与邪恶()同义,最好避免使用它。
所以我想知道:有没有更好的方法来做到这一点?
多谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试
Try