3 回答
TA贡献1827条经验 获得超8个赞
覆盖您的get_serializer_class方法。您的模型mixins中使用此方法来检索适当的Serializer类。
请注意,还有一种get_serializer方法可以返回正确的Serializer 的实例
class DualSerializerViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == 'list':
return serializers.ListaGruppi
if self.action == 'retrieve':
return serializers.DettaglioGruppi
return serializers.Default # I dont' know what you want for create/destroy/update.
TA贡献1877条经验 获得超6个赞
您可能会发现此mixin有用,它覆盖了get_serializer_class方法,并允许您声明一个将操作和序列化程序类或后备映射到常规行为的字典。
class MultiSerializerViewSetMixin(object):
def get_serializer_class(self):
"""
Look for serializer class in self.serializer_action_classes, which
should be a dict mapping action name (key) to serializer class (value),
i.e.:
class MyViewSet(MultiSerializerViewSetMixin, ViewSet):
serializer_class = MyDefaultSerializer
serializer_action_classes = {
'list': MyListSerializer,
'my_action': MyActionSerializer,
}
@action
def my_action:
...
If there's no entry for that action then just fallback to the regular
get_serializer_class lookup: self.serializer_class, DefaultSerializer.
"""
try:
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super(MultiSerializerViewSetMixin, self).get_serializer_class()
- 3 回答
- 0 关注
- 1558 浏览
添加回答
举报