While working in my last project i needed to do some query using the "or" conditional depending on what keywords the user had selected.
For that matter the best i could find was django-filter, this app allows you to make from simple to complex queries to your database in an easy way.
First you must install the app in your project with the command:
pip install django-filter
Set the app in your settings.py file:
In my particular case i was using a custom user, here you have the model:
According to django-filter documentation you have to create a file named filters.py and set the following:
At the top of the file import:
import django_filters
from django.forms.widgets import TextInput
Then i created the filter class:
I have to mention that the import i did from django forms was to show a placeholder named "search..." in the form input field in the template.
So here in the above class i use a custom filter function that receives a value from the Q field of the form in the front end.
You must specify the model you are querying.
To render the form in the template is has to be in this format:
Then to process the info coming from the template you have to create a view, mine is as follows:
The result of this code will allow us to search for any data we specify in the filter, in my case "First_name, last_name or email".
If you want to know more about complex lookups here you have the link Django Docs.
I hope you like the article, please leave your comment :-)