zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Django模糊查询「建议收藏」

django 查询 建议 收藏 模糊
2023-06-13 09:11:51 时间

大家好,又见面了,我是你们的朋友全栈君。

模糊查询:

def search(request):
    searchtype = request.POST.get("searchtype")
    keyword = request.POST.get("keyword")
    if searchtype == "all":
        #多个字段模糊查询, 括号中的下划线是双下划线,双下划线前是字段名,双下划线后可以是icontains或contains,区别是是否大小写敏感,竖线是或的意思
        sciencenews = models.Sciencenews.objects.filter(Q(title__icontains=keyword)\
		|Q(content__icontains=keyword)|Q(author__icontains=keyword))
    elif searchtype == "author":
        #单个字段模糊查询
        sciencenews = models.Sciencenews.objects.filter(author__icontains=keyword)
    elif searchtype == "title":
        sciencenews = models.Sciencenews.objects.filter(title__icontains=keyword)
    elif searchtype == "content":
        sciencenews = models.Sciencenews.objects.filter(content__icontains=keyword)
	else:
		#使用点连接的filter链表示and
		sciencenews = models.Sciencenews.objects.filter(author__icontains=keyword).\
			filter(title__icontains=keyword).filter(content__icontains=keyword)
		
    return render(request,"show/index.html",{"param":sciencenews,"searchtype":searchtype,"keyword":keyword})

参考文章: http://www.guojl.com/article/13/ https://www.douban.com/note/505215076/ http://xinleisky.blog.sohu.com/244421023.html http://blog.sina.com.cn/s/blog_9e2e84050101j3ch.html

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139249.html原文链接:https://javaforall.cn