Reputation: 2784
On django 2.2.3 would it be possible to combine the startswith and in filter s?
I need to check if the value startswith from a list.
IGNORA = ['xx','yy.', ]
# something like this
model.filter(value__istartswith__in=IGNORA)
def check_code(codice):
for x in IGNORA:
if codice.startswith(x):
return True
return False
Can it be done someway?
Upvotes: 0
Views: 91
Reputation: 3378
Your query is a complex one, you can use Q
to handle some complex query like yours.
Thanks for reduce function tool, which you can use to iterate over your IGNORA
to create startswith
query and then you can make in
query as normal way. E.g:
from django.db.models import Q
from functools import reduce
from operator import or_
IGNORA = ['xx','yy.', ]
filter_model = Model.objects.all()
for txt in IGNORA:
filter_model = filter_model.filter(value__istartswith=txt)
result = filter_model
Hope that helps!
Upvotes: 0
Reputation: 476659
No, you can however write your a query that "unwinds" the list, into multiple conditions where you put a logical or in between:
from django.db.models import Q
from functools import reduce
from operator import or_
IGNORA = ['xx','yy.', ]
def q_or_iterable(key, iterable):
if iterable:
return reduce(or_, (Q(**{key: item}) for item in iterable))
else:
Q(pk__in=())
Model.objects.filter(q_or_iterable('value__istartswith', IGNORA))
Upvotes: 1