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')
)
- [Django]-'Cannot alter upload handlers' while trying to upload file
- [Django]-Django – Exception Value: Unexpected end of expression in if tag
- [Django]-Django – Model with 2 foreign keys from the same class
- [Django]-Return data in httpresponse for ajax call in Deleteview in django?
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)
- [Django]-Make celery wait for task to finish
- [Django]-405 POST method no allowed on heroku with django
- [Django]-Nginx permission denied 13 with Django on static content
- [Django]-Get latest object with filter in django rest framework
- [Django]-How to convert Foreign Key Field into Many To Many Field without disturbing existing data in the database?
Source:stackexchange.com