我正在创建一个基本视图集类,并尝试在两个类中使用它。视图集有一个create方法,该方法使用get_serializer_class((来获取serializer并创建对象。但是is_valid((抛出错误
TypeError:BaseSerializer.is_valid((缺少1个必需的位置参数:"self">
这是基类:
class BaseViewSet(BaseFilterViewSet):
permission_classes = [IsAuthenticated]
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
context = super(BaseViewSet, self).get_serializer_context()
context.update({"request": request})
# serializer = super(BaseViewSet, self).get_serializer_class()
serializer = self.get_serializer_class()
serializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
serializer.save(created_by=request.user)
return Response(serializer.data, status=HTTP_201_CREATED)
下面是使用此视图集并定义get_serializer_class方法的子类。
class ChildViewSet(BaseViewSet):
queryset = Child.objects.all().select_related("model2")
permission_classes = [IsAuthenticated]
def get_serializer_class(self) -> Type[BaseSerializer[_MT_co]]:
if self.action == "stock":
return StockSerializer
else:
return ChildSerializer
非常感谢您的投入和帮助。
您可以使用.get_serializer(…)
[drf-doc]:这将使用.get_serializer_class()
[drf-doc][sup>中指定的序列化程序类自动创建序列化程序,该类具有已包含请求(以及view
和format
(的.get_serializer_context(…)
方法调用/drf-doc]/sup>检索的上下文。因此,您可以将其实现为:
class BaseViewSet(BaseFilterViewSet):
permission_classes = [IsAuthenticated]
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(created_by=request.user)
return Response(serializer.data, status=HTTP_201_CREATED)