普拉多VX

人生一路,不问来时,不知归期

0%

django DRF根据方法调用不同的serializer

根据不同参数调用不同

自定义get_serializer_class方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

class QueryItemsView(ListAPIView):
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)


def get_serializer_class(self):
if self.post_type == 'port':
return serializers.ServerPortItemsSerializer
elif self.post_type == 'web':
return serializers.WebItemsSerializer
elif self.post_type == 'ssl':
return serializers.SslCertSerializer
else:
return serializers.WebItemsSerializer

def get_queryset(self):

self.post_type = self.request.GET.get('item_type', 'port')

if self.post_type == "port":
queryset = ServerPortItems.objects.filter(uid=self.request.user.id).order_by('-create_at')
elif self.post_type == 'web':
queryset = ServerWebItems.objects.filter(uid=self.request.user.id).order_by('-create_at')
elif self.post_type == 'ssl':
queryset = ServerSslcertItems.objects.filter(uid=self.request.user.id).order_by('-create_at')
else:
queryset = ServerPortItems.objects.filter(uid=self.request.user.id).order_by('-create_at')

return queryset

当然也可以根据不同的逻辑实现调用不同的放,比如请求类型GET/POST

1
2
3
4
5
6
def get_serializer_class(self):
"""重写获取序列化器类的方法"""
if self.request.method == "GET":
return Model2Serializer
else:
return ModelSerializer