Django搜索栏的多字段过滤实现



我正在尝试实现搜索栏的功能。

我的models.py:

class Question(models.Model):
questionId = models.IntegerField(primary_key=True)
groupId = models.IntegerField(default=0)
questionTitle = models.TextField()
groupName = models.CharField(max_length=500, null=True, blank=True)
correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses")

我的数据库很大,所以我尝试跳过Question.objects.all()以节省时间。

我的views.py:

def questionList(request)
# Searching Any Value
if request.method == "POST" and request.POST['searchKey'] != '':
searchKey = request.POST['searchKey']
questions = Question.objects.filter(questionId=searchKey)
return render(request,'diagnosis/questionList.html', {'questions': questions})

这是非常有效的,但它只能通过questionId进行过滤。我希望有这样一个搜索栏,它将通过匹配Question模型的所有字段(questionIdgroupIdquestionTitle…等等(进行过滤。(注意:request.GET已用于分页。(

请建议我该怎么做?

使用Q对象进行更复杂的查找。

from django.db.models import Q
def questionList(request)
# Searching Any Value
if request.method == "POST" and request.POST['searchKey'] != '':
searchKey = request.POST['searchKey']
try:
# tries to convert key into int
searchKey = int(searchKey)
# returns a Queryset with Question objects where any of the fields match the searchKey
questions = Question.objects.filter(Q(questionId=searchKey) | Q(groupId=searchKey))
except:
# if key is not a number, don't query integer fields
questions = Question.objects.filter(questionTitle=searchKey)
return render(request,'diagnosis/questionList.html', {'questions': questions})

最新更新