[Django]-Django filter, many queries in array

3👍

✅

You can do it with dictionary like this:

filters = Q()

val_arr = dict()
val_arr.update({"question__startswith": 'Who'))
val_arr.update({"question__startswith": 'What'))

for item in val_arr:
   filters |= Q(**{item:val_arr[item]})

Anime.objects.filter(filters)

2👍

Instead of & (AND) operation, using | (OR) will solve your issue

So change

Anime.objects.filter(
    Q(question__startswith='Who') & Q(question__startswith='What')
)

to

Anime.objects.filter(
    Q(question__startswith='Who') | Q(question__startswith='What')
)

2👍

Investigate the well-known django-filters package. It may already do everything you want, allowing a user to construct his own complex queries in a view.

What you ask can be coded using the | or operator

q = val_arr[0]
for val in val_arr[1:] :
    q = q | val

Anime.objects.filter( q)

You need to | your Q objects together. The same question cannot start both with ‘Who’ and with ‘What’. qs.filter(field1=val1, field2=val2) is and-logic and you can also this by Q(field1=val1)&Q(field2=val2)

Leave a comment