[Answer]-How to add more conditions in where clause?

0đź‘Ť

âś…

I think you need to escape the % sign in your query:

' and level_concat like %%'+level+'%%'
👤Aamir Rind

1đź‘Ť

Firstly, it is not a good practice to keep data in a relational database as a “list of [values] concatenated by coma” – you should create a new table for those values.

Still, even now you can use filter(), instead of extra() (which should be always your last resort – I don’t see the rest of your code, but if you don’t properly escape levels values you may even be introducing an SQL Injection vulnerability here).

An example of a secure, extra()-less code, that does the exact same thing:

from django.db.models import Q

q = Q()
for level in levels:
    q &= Q(level_concat__contains=level)

countries = Country.objects.filter(q)

or the same functionality, but in even less number of lines:

from django.db.models import Q

q = (Q(level_concat__contains=l) for l in levels)
countries = Country.objects.filter(*q)

You can read more about Q object in Django docs.

Leave a comment