Keyword arguments queries with Django framework and django-filters app
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:
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
profile_picture = models.ImageField(default='profile_default.png', upload_to='profile_pics/', blank=True, null=True)
request_info = models.TextField()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
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:
class MemberSearchFilter(django_filters.FilterSet):
q = django_filters.CharFilter(method='CustomFilter', label="", widget=TextInput(attrs={'placeholder': 'Search...'}))
class Meta:
model = CustomUser
fields = ['q']
def CustomFilter(self, queryset, name, value):
return CustomUser.objects.filter(
Q(first_name__icontains=value)| Q(last_name__icontains=value) | Q(email__icontains=value)
)
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:
<form method="get">
{{ filter.form}}
</form>
Then to process the info coming from the template you have to create a view, mine is as follows:
@login_required
def member_list_filter_backend(request):
"""Note: i make the ordering inverse by date_joined to see the last members added"""
f = MemberSearchFilter(request.GET, queryset=CustomUser.objects.all().order_by('-date_joined'))
return render(request, 'eow/members_list.html', {'filter': f})
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 :-)