Django项目实战 - 搜索功能

首先,前端已实现搜索功能页面, 我们直接写后台逻辑:

 

Q()可以实现 逻辑或的判断,   name_ _ icontains 表示 name字段包含搜索的内容,i表示忽略大小写。

from django.db.models import Q

all_orgs
= CourseOrg.objects.all() search_keywords = request.GET.get("keywords", "") if search_keywords: all_orgs = all_orgs.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords))

 需要注意的是:

、Q对象可以与关键字参数查询一起使用,不过一定要把Q对象放在关键字参数查询的前面。
    # 正确:
    Book.objects.get(
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
        title__startswith='P')
    # 错误:
    Book.objects.get(
        question__startswith='P',
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))

 


 

posted @ 2017-03-06 22:10  Vincen_shen  阅读(2985)  评论(0)    收藏  举报