3

need an array where Q() object are added filter with many value

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

but need something like this

val_arr = []
val_arr.append(Q(question__startswith='Who'))
val_arr.append(Q(question__startswith='What'))
Anime.objects.filter(val_arr)
1
  • can you elaborate more. your question is unclear. Commented Jan 14, 2022 at 18:17

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

how did you declare the filters variable. local variable 'filters' referenced before assignment
Updated the answer check
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')
)

Comments

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)

1 Comment

that's a good solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.