多个查询字符串参数

Multiple querystring parameters

我创建了这个简单的搜索功能:

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")

当我只使用一个条件时,例如:

 posts = Blog.objects.filter(title__icontains=querystring) 

它向我展示了正确的结果。但是当我使用多个参数时,我有 SyntaxError: invalid syntax

我确定查询对应于:

SELECT * FROM Post WHERE "title" is "key_search" or "tagline" is "key_search" or "contents" is "key_search"

我该如何解决?

以上是不正确的 Python 语法,您不能在命名参数之间放置运算符。

Django 然而有 Q objects [Django-doc] 来表达 "conditions",所以你可以将条件包装在 Q 对象中,并使用 | 运算符来表达逻辑或,喜欢:

from django.db.models import <b>Q</b>

posts = Blog.objects.filter(
    <b>Q</b>(title__icontains=querystring) |
    <b>Q</b>(tagline__icontains=querystring) |
    <b>Q</b>(contents__icontains=querystring)
)

这将导致查询看起来或多或少类似于:

SELECT *
FROM Post
WHERE "title" LIKE "%key_search%"
   OR "tagline" LIKE "%key_search%"
   OR "contents" LIKE "%key_search%"