sumit roy
sumit roy

Reputation: 11

I want to make two queryset search in Django

Using django.Filter() to search or filter the details of posts already saved in django.

Using Q of django to make search in queryset. using checkbox, so that this filter(), to add a filter in my webpage when --

/?q=Bangalore

Im getting correct value as

LOCATION  BANGALORE  PUNE 
ujjwal
56789
[email protected]
bottle
bisleri
bangalore
Sept. 20, 2018, 3 p.m.

but when I am selecting both of the checkbox and perform search:

?q=Bangalore&q=Pune

if you notice the above url , it is performing '&' (and) opertion and, rather i want to show in search, the data of either of the value. Suppose, in database only, Bangalore is saved but not pune or vice-versa. It is showing nothing . ..

my code:

if query:
   queryset = queryset.filter(
   Q(Name__icontains = query) |      
   Q(Location__icontains= query) ) 

Hope I am able to make you understand my situation..

Upvotes: 1

Views: 96

Answers (2)

Will Keeling
Will Keeling

Reputation: 23054

I think you should be able to do something such as this:

from functools import reduce

query = request.GET.getlist('q')

queryset = queryset.filter(
    reduce(lambda x, y: x | y,
           [Q(Name__icontains=q) | Q(Location__icontains=q) for q in query]
    )
)

That will build up a Q object, or-ing each search term together.

Upvotes: 1

aasmpro
aasmpro

Reputation: 604

as the Django Document says, you can use this code to access a list of query_params witch have same key:

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]

also checkout this answer too.

Upvotes: 0

Related Questions