Better than eval () when translating keyword arguments into QuerySets (Python / Django)

I use django-transmeta (could not get something to work better with django 1.2.5), which creates several columns in the table, for example: content_en, content_es, content_it

Before i18n implementation, I had:

items = Items.objects.filter(categories__slug=slug) 

now category.slug is international, so I have "category.slug_en", "category.slug_es", "category.slug_it", etc.

So even though I do:

 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 when I need to add a new language, I will have to change the code and, of course, I do not want to do this.

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 use eval (), which, of course, is synonymous with evil (), and it would be better to avoid it.

So I was wondering: is there a better way to do this?

Thanks a lot!

+4
source share
1 answer

Try

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

Source: https://habr.com/ru/post/1340977/


All Articles