DRF教程8-过滤
在写后端api时,经常需要使用各种过滤条件,可以使用Q对查询集进行过滤,这里介绍一个新玩意儿
以下是基础文档
https://django-filter.readthedocs.io/en/master/index.html
过滤条件:
https://blog.csdn.net/chen1042246612/article/details/84071139
以django自带的用户类为例
serializers.py
from rest_framework import serializers class UserSerializer(serializers.Serializer): """ 用户序列化类 """ id = serializers.IntegerField() username = serializers.CharField()
users/filters.py
import django_filters # 导入过滤器,需要先pip安装 from django.contrib.auth import get_user_model User = get_user_model() # user model class UserFilter(django_filters.FilterSet): # 过滤username参数,精确过滤, lookup_expr='contains'为模糊查询, # 默认大小写敏感,可以加i让其大小写不敏感 username = django_filters.CharFilter(name="username", lookup_expr='contains') class Meta: model = User fields = ['username']
views.py
from rest_framework import viewsets from django.contrib.auth import get_user_model User = get_user_model() from .serializers import UserSerializer from .filters import UserFilter class UserViewset(viewsets.ReadOnlyModelViewSet): """ retrieve: 返回指定用户信息 list: 返回用户列表 """ queryset = User.objects.all() serializer_class = UserSerializer filter_class = UserFilter filter_fields = ("username",)