python关键字eval_当在QuerySets(Python / Django)中翻译关键字参数时,比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!

解决方案

Try

q = Q(**{"categories__slug_" + current_lang + "__contains": slug})

items = Items.objects.filter(q)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值