I am writing a small search engine for my page in django.
my query code:
sterm = request.GET.get('searchterm')
books = Book.objects.filter(title__iregex=r"\y{0}\y".format(sterm))
One issue with this code is, if I search for "python test"
, it is giving me only books which have "python test"
in their title. But I also need books which have only "python"
or "test"
in their title. I know, I can use Q
. But i am in need for some efficient lookup, i am thinking about this logic:
sterms = sterm.split()
if len(sterms) == 1:
books = Book.objects.filter(title__iregex=r"\y{0}\y".format(sterm))
else:
for each in sterms:
## how can I gather here all Q's?
#then this?
books = Book.objects.filter("gathered Q's with |")
how can I gather Q
filters and then pass it to query? am I ok with this logic or is there more efficient and cooler way of doing this?