Reputation: 1290
I've created this simple search function:
def search(request):
if "q" in request.GET:
querystring = request.GET.get("q")
print(querystring)
if len(querystring) == 0:
return redirect("/search/")
posts = Blog.objects.filter(title__icontains=querystring | tagline__icontains=querystring | contents__icontains=querystring)
context= {"posts": posts}
return render(request, "kernel/search.html", context)
else:
return render(request, "kernel/search.html")
When I use only one condition, for example:
posts = Blog.objects.filter(title__icontains=querystring)
it's shown me the correct results. But when I use multiple parameters I have SyntaxError: invalid syntax.
I was sure the query corresponded to:
SELECT * FROM Post WHERE "title" is "key_search" or "tagline" is "key_search" or "contents" is "key_search"
How I can resolve?
Upvotes: 1
Views: 167
Reputation: 476594
The above is incorrect Python syntax, you can not put operators between named parameters.
Django however has Q
objects [Django-doc] to express "conditions", so you can wrap the conditions in Q
objects, and use the |
operator to express a logical or, like:
from django.db.models import Q
posts = Blog.objects.filter(
Q(title__icontains=querystring) |
Q(tagline__icontains=querystring) |
Q(contents__icontains=querystring)
)
This will result in a query that looks, more or less, like:
SELECT *
FROM Post
WHERE "title" LIKE "%key_search%"
OR "tagline" LIKE "%key_search%"
OR "contents" LIKE "%key_search%"
Upvotes: 2