[英]Django search bar implementation with multiple field filtering
我正在嘗試實現搜索欄的功能。
我的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
模型具有的所有字段( questionId
、 groupId
、 questionTitle
... 等等)進行過濾。 (注意: request.GET
已經用於分頁。)
請建議我該怎么做?
使用Q Objects進行更復雜的查找。
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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.