Now that all of you are back at work, we are going to get back to Python development technology. After all, this is what we eat.
Today we are going to talk about a package called Django-filter that I use every day. Django-filter is a very handy package for filtering Django applications. It only takes a few lines of code to do the filtering.
I introduced Swagger in front of the article “super easy to use API tool -Swagger” when mentioned it, especially for XXX system management page processing is not too convenient, and listen to me carefully.
Install the configuration
The tool is easy to install via PIP
pip install django-filter
Djangofilter 1.1.0 is required if your environment is Python2.7. This package relies on the DjangorestFramework framework. I’m going to call it DRF for short.
Once installed, we added INSTALLED_APPS
# settings.py
INSTALLED_APPS = [
...
'rest_framework',
'django_filters',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
...
),
}
Copy the code
Here django-filter is used as the default backends. You can also write it in viewSet, see below.
use
To do this, we need to create a FilterSet class for filtering. Without further ado, let’s look at the code.
from rest_framework import generics from django_filters import rest_framework as filters from myapp import Product class ProductFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='lte') class Meta: model = Product fields = ['category', 'in_stock', 'min_price', 'max_price']Copy the code
The above code shows our price range filtering, but in practice we can do more filtering displays,
class ProductFilter(django_filters.rest_framework.FilterSet): class Meta: model = Product fields = { 'order_id': ['exact'], 'status': ['in'], 'created_at': ['range'], 'card__company_name': ['contains'], 'card__email': ['exact'], } class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) # # filterset_class = ProductFilter # django-filter 2.1 Python3 filter_class = ProductFilter # django-filter 1.1, python2.7Copy the code
Django-filter (filterset_class) : django-filter (filterset_class) : django-filter (filterset_class) Filter_class was written prior to version 1.1.
The effect
As you can see from the above code, we’ve improved our back-end efficiency by integrating Django-Filter into DRF to make daily filtering easier and more efficient. I can not only carry out development and debugging but also deliver a complete interface to the front end of the students, so that we are more happy to connect.
Combined with the Swagger I mentioned above, the effect picture is as follows.