我正在尝试在端点中使用两个不同的序列化程序,但我指定的第二个序列化程序(UserSerializer)是正在使用的序列化程序.有没有办法让一个特定的序列化程序用于一个特定的模型,以便我可以使用userSerializer来创建用户,使用CategorySerializer来创建一个类别.
class UserSignup(generics.CreateAPIView):
model = Category
serializer_class = CategorySerializer
model = User
serializer_class = UserSerializer
def create(self, request):
data = request.data
category_serializer = self.get_serializer(data=request.data, many=True)
user_serializer = self.get_serializer(data=request.data, many=True)
最佳答案 在一个API视图中只能有一个序列化程序类.如果想要使用两个序列化程序,您可以像这样使用它.
class UserSignup(generics.CreateAPIView):
model = Category
serializer_class = CategorySerializer
def create(self, request):
data = request.data
category_serializer = self.get_serializer(data=request.data, many=True)
user_serializer = UserSerializer(data=request.data, many=True)
或者如果真的想要为第二个序列化器提供一些方法,你可以这样做
class UserSignup(generics.CreateAPIView):
model = Category
serializer_class = CategorySerializer
def get_user_serializer(*args, **kwargs):
# you can have some logic here...
return UserSerializer(*args, **kwargs)
def create(self, request):
data = request.data
category_serializer = self.get_serializer(data=request.data, many=True)
user_serializer = self.get_user_serializer(data=request.data, many=True)