Home > other >  Django filter, many queries in array
Django filter, many queries in array

Time:01-15

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)

CodePudding user response:

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)

CodePudding user response:

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')
)

CodePudding user response:

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)

  •  Tags:  
  • Related