How to Search Multiple Database Fields in Django
Let's say you are working on a search function for your Django project and would like to search for items based on their title and description. To do this you'll need to create Q
objects and pass them into your fiilter function.
Let's try this out by filtering by keyword using two fields.
myproject/src/app/views.py
q = 'hello'
obj = MyModel.objects.filter(Q(name__icontains=q) | Q(description__contains=q))
Replace MyModel
with the name of the model you wish to search through. The object returned will be a list of the matching items found in the table.
To add another pass it in using a |
(pipe) then create a Q
object containing myField__contains=
and the value to search.
Full Search Function Example
Here is a complete example function that grabs the search keyword from the q get request parameter and searches multiple fields.
myproject/src/app/views.py
def search(request, *args, **kwargs):
q = request.GET['q']
obj = MyModel.objects.filter(Q(name__icontains=q) | Q(description__contains=q), status=True)
context = {
'object': obj,
'q': q
}
return render(request, 'search.html', context)
django