- 當viewset中,多個action對應了不一樣的serializers的時候
class UserView(viewsets.GenericViewSet):
queryset = User.objects.all()
serializer_class = UserSeriallers
def get_serializer_class(self):
if self.action in ['collection', ]:
return Serializers1
elif self.action in ['orderhouse', ]:
return Seriallers2
elif self.action in ['disperson', ]:
return Serializers3
return self.serializer_class
- 當viewset中,多個action對應不一樣的permission
class AdviserView(viewsets.GenericViewSet):
queryset = Adviser.objects.all().order_by("-id")
serializer_class = AdviserSerializers
permission_classes = (AdviserPermission, )
def get_permissions(self):
if self.action in ["small_app_login", "decode_data",
"bind_phone"]:
self.permission_classes = ()
return super().get_permissions()
- 若是不習慣class view的方式可使用@api_view裝飾器,對應的權限等class能夠經過對應的裝飾器添加
- serializer中,使用SerializerMethodField,若是須要使用request的數據,能夠經過
self.context['request']
取出來,一樣的,若是serializer中須要將request傳到context, 使用serializers的時候 須要serializer = Serializer(qs, many=True, context={ 'request': request})
的方式傳入context
- 當列表的serializer和詳情的serializer的字段不一樣時,可使用繼承的方式,減小代碼量