2021-10-21 08:16:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
|
|
|
from rest_framework.request import Request
|
|
|
|
|
2021-10-21 08:39:52 +00:00
|
|
|
__all__ = ['SerializerMixin']
|
2021-10-21 08:16:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SerializerMixin:
|
|
|
|
""" 根据用户请求动作的不同,获取不同的 `serializer_class `"""
|
|
|
|
|
|
|
|
action: str
|
|
|
|
request: Request
|
|
|
|
|
|
|
|
serializer_classes = None
|
|
|
|
single_actions = ['put', 'retrieve', 'patch']
|
|
|
|
|
2022-04-06 03:29:16 +00:00
|
|
|
def get_serializer_classes(self):
|
2022-05-04 01:57:45 +00:00
|
|
|
classes = getattr(self, 'serializer_classes', None) or {}
|
|
|
|
return dict(classes)
|
2022-04-06 03:29:16 +00:00
|
|
|
|
2021-10-21 08:16:50 +00:00
|
|
|
def get_serializer_class_by_view_action(self):
|
2022-04-06 03:29:16 +00:00
|
|
|
serializer_classes = self.get_serializer_classes()
|
|
|
|
if serializer_classes is None:
|
2021-10-21 08:16:50 +00:00
|
|
|
return None
|
2022-05-04 01:57:45 +00:00
|
|
|
if not isinstance(serializer_classes, dict):
|
2021-10-21 08:16:50 +00:00
|
|
|
return None
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_classes = dict(serializer_classes)
|
2021-10-21 08:16:50 +00:00
|
|
|
view_action = self.request.query_params.get('action') or self.action or 'list'
|
2024-04-02 07:55:08 +00:00
|
|
|
if self.request.query_params.get('format'):
|
|
|
|
view_action = 'retrieve'
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_class = serializer_classes.get(view_action)
|
2021-10-21 08:16:50 +00:00
|
|
|
|
|
|
|
if serializer_class is None:
|
|
|
|
view_method = self.request.method.lower()
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_class = serializer_classes.get(view_method)
|
2021-10-21 08:16:50 +00:00
|
|
|
|
|
|
|
if serializer_class is None and view_action in self.single_actions:
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_class = serializer_classes.get('single')
|
2021-10-21 08:16:50 +00:00
|
|
|
if serializer_class is None:
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_class = serializer_classes.get('display')
|
2021-10-21 08:16:50 +00:00
|
|
|
if serializer_class is None:
|
2022-05-04 01:57:45 +00:00
|
|
|
serializer_class = serializer_classes.get('default')
|
2021-10-21 08:16:50 +00:00
|
|
|
return serializer_class
|
|
|
|
|
|
|
|
def get_serializer_class(self):
|
|
|
|
serializer_class = self.get_serializer_class_by_view_action()
|
|
|
|
if serializer_class is None:
|
|
|
|
serializer_class = super().get_serializer_class()
|
|
|
|
return serializer_class
|