1

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?

1 Answer 1

2

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%"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.