安装及注册
pip install django-filter
INSTALLED_APPS = [...\'django_filters\',...]
示例model
class User(models.Model):# 模型字段name = models.CharField(max_length=10, verbose_name=\"姓名\")sex = models.BooleanField(default=1, verbose_name=\"性别\")age = models.IntegerField(verbose_name=\"年龄\")phone = models.CharField(max_length=20, null=True, verbose_name=\"电话\")addr = models.CharField(max_length=100,null=True,verbose_name=\"地址\")class Meta:db_table = \"tb_user\"verbose_name = \"用户\"verbose_name_plural = verbose_name
过滤
方式一
视图层直接设置过滤字段
示例:
# 以name和age过滤class UserViewSet(ModelViewSet):queryset = User.objects.all()serializer_class = UserModelSerializerfilter_backends = (DjangoFilterBackend,)filter_fields = (\'name\', \'age\')
filter_backends 配置过滤器,也可以在setting.py文件全局配置
# 这样REST_FRAMEWORK = {\'DEFAULT_FILTER_BACKENDS\': (\'django_filters.rest_framework.DjangoFilterBackend\',) #全局默认配置过滤}
filter_fields
设置过滤字段,这里设置了name和age
这里设置的是对字段的精确过滤
方式二
新建一个filter.py文件
import django_filtersfrom user.models import Userclass UserFilter(django_filters.FilterSet):class Meta:model = Userfields = [\"name\", \"age\"]
更改视图
class UserViewSet(ModelViewSet):queryset = User.objects.all()serializer_class = UserModelSerializerfilter_backends = (DjangoFilterBackend,)# filter_fields = (\'name\', \'age\')filter_class = UserFilter # 指定过滤器类
模糊过滤
class UserFilter(django_filters.FilterSet):class Meta:model = User# fields = [\"name\", \"age\"]fields = {\"name\": [\'exact\',\'icontains\'],\"age\": [\'exact\'],}
exact:默认过滤方式,精确过滤
icontains:模糊过滤
范围过滤
class UserFilter(django_filters.FilterSet):# name_mh = django_filters.CharFilter(field_name=\'name\',lookup_expr=\'icontains\')# age_gt = django_filters.NumberFilter(field_name=\'age\', lookup_expr=\'gt\')# age_lt = django_filters.NumberFilter(field_name=\'age\', lookup_expr=\'lt\')class Meta:model = User# fields = [\"name\", \"age\"]fields = {\"name\": [\'exact\',\'icontains\'],\"age\": [\'exact\',\'gte\',\'lte\'],}
生成的过滤器
name 精确查找
name__icontains 模糊查找
age
age__gte 大于等于
age__lte 小于等于
gt 大于gte 大于等于lt 小于lte 小于等于对于日期year__gtmonth__gtday__gt
排序
class UserFilter(django_filters.FilterSet):# name_mh = django_filters.CharFilter(field_name=\'name\',lookup_expr=\'icontains\')sort = django_filters.OrderingFilter(fields=(\'age\',))# age_gt = django_filters.NumberFilter(field_name=\'age\', lookup_expr=\'gt\')# age_lt = django_filters.NumberFilter(field_name=\'age\', lookup_expr=\'lt\')class Meta:model = User# fields = [\"name\", \"age\"]fields = {\"name\": [\'exact\',\'icontains\'],\"age\": [\'exact\',\'gte\',\'lte\'],}