如何使用多个关键字在django中查询数据库
我有一个Job模型,有这样的类
class Job(models.Model):
title = models.CharField(max_length=100)
我想查询jobs_job数据库以实现搜索功能
def search(request):
if request.method == "GET":
search_terms = request.GET['title']
search_terms = search_terms.split(',')
jobs = Job.objects.filter(title__contains=search_terms[0])
问题是我只能将一个项目传递给contains
方法,
如何使用多个单词搜索作业模型标题属性
答案 0 :(得分:1)
例如你可以做
from django.db.models import Q
def search(request):
if request.method == "GET":
search_terms = request.GET['title']
search_terms = search_terms.split(',')
#get rid of duplicates
search_terms = set(search_terms)
queryargs = [Q(title__contains=i) for i in search_terms]
jobs = Job.objects.filter(*queryargs)
答案 1 :(得分:1)
使用django.db.models.Q
个对象。像这样:
from django.db.models import Q
def search(request):
if request.method == "GET":
search_terms = request.GET['title']
search_filter = Q()
for term in search_terms.split(','):
search_filter |= Q(title__contains=term)
jobs = Job.objects.filter(search_filter)
这将搜索任何条款(OR),以搜索所有条款(AND)而不是search_filter &= Q(title__contains=term)
。