如何使用“或”语句进行查询

时间:2018-10-26 14:06:34

标签: django django-queryset

我有一个示范文章,在文章中我有标题和文章

我具有搜索功能,无论搜索的类型是什么,都必须让我在标题或文章中包含搜索文本的所有文章

def searh(request):
    print(request.POST)
    kw = request.POST['search']
    articles = Article.objects.filter(title__contains=kw).filter(article__contains=kw)
    context = {'News':articles}
    return render(request, 'menu/search_results.html', context )

此查询不准确不会同时返回if

如何构造它?

  articles = Article.objects.filter(title__contains=kw).filter(article__contains=kw)

我的搜索表

            <form method="POST" class="search-box" action="{% url 'search' %}">
                {% csrf_token %}
                <input  class="site-search" type="text" placeholder="{% trans 'Търси..' %}" name="search">
                <button type="submit"><i class="fa fa-search"></i></button>
            </form>

1 个答案:

答案 0 :(得分:3)

在我看来,您必须使用:

from django.db.models import Q

def search(request):
    kw = request.POST.get('search')
    articles = Article.objects.filter(Q(title__contains=kw) | Q(article__contains=kw))
    context = {'News':articles}
    return render(request, 'menu/search_results.html', context )