①ViewSet不经过Swagger传参给serializer
②ViewSet自定义filter用于筛选request中数据
1. filter.py
class TeacherFilterBackend(BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
if not request.user.is_authenticated:
return queryset.none()
school = request.user.school
if school:
queryset = queryset.filter(school=school)
return queryset
else:
return queryset.none()
2. views.py
class TeacherViewSet(ListAPIView, GenericViewSet):
'''测试获取列表'''
filter_backends = [TeacherFilterBackend]
queryset = Teacher.objects.all()
serializer_class = TeacherSerializer
permission_classes = [DjangoModelPermissions]
def get_serializer_context(self):
return {'name': self.request.GET.get("name")}
3. serializer.py
# 测试获取列表序列化
class TeacherSerializer(serializers.ModelSerializer):
status = serializers.SerializerMethodField()
def get_status(self,obj):
name = self.context['name']
try:
obj.students_set.get(name=name)
return "1"
except:
return "0"