Django search bar implementation with multiple field filtering

Viewed 55

I am trying to implement the functionality of a search bar.

my 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")

My database is huge, so I tried to skip Question.objects.all() to save time.

my 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})

This works perfectly but it can only filter by questionId. I wish to have such a search bar that will filter by matching all the fields(questionId, groupId, questionTitle... etc all) the Question model has. (note: request.GET already been used for pagination.)

Please suggest how can I do this?

1 Answers

Use Q Objects for more complex lookups.

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})
Related