3

你是我针对不同用户的序列化程序

class PlayerSerializer(serializers.ModelSerializer):   
       class Meta:
            model = player
            fields = ('contact_name', 'contact_email', 'address',)


class ManagerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Manager
        fields = ('contact_name', 'contact_email', 'address',
                  'city', 'country',)


class CoachSerializer(serializers.ModelSerializer):

    class Meta:
        model = Shipper
        fields = (' 'contact_name', 'contact_email', 'address', 'city', 'about', 'country',)


these are my user Serializers with relation with each user type 

class playerUserSerialzers(serializers.ModelSerializer):
   player =PlayerSerializer()

    class Meta:
        model = MyUser
        fields = ('email', 'id', 'password', 'player',)
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        player_data = validated_data.pop('player')
        user = MyUser(
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user = MyUser.objects.create(**validated_data)
        Player.objects.create(user=user, **player_data)
        user.save()
        return user


class managerUserSerialzers(serializers.ModelSerializer):
   manager =ManagerSerializer()

    class Meta:
        model = MyUser
        fields = ('email', 'id', 'password', 'manager',)
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        manager_data = validated_data.pop('manager')
        user = MyUser(
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user = MyUser.objects.create(**validated_data)
        Manager.objects.create(user=user, **manager_data)
        user.save()
        return user


class managerUserSerialzers(serializers.ModelSerializer):
  coach =CoachSerializer()

    class Meta:
        model = MyUser
        fields = ('email', 'id', 'password', 'coach',)
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        coach_data = validated_data.pop('coach')
        user = MyUser(
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user = MyUser.objects.create(**validated_data)
       Coach.objects.create(user=user, **coach_data)
        user.save()
        return user

这不起作用,但我想根据前端请求使用不同的序列化程序

class MyUserViewSet(mixins.CreateModelMixin,
                        mixins.RetrieveModelMixin,
                        mixins.DestroyModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.ListModelMixin,
                        GenericViewSet):
        queryset = MyUser.objects.all()
        pagination_class = LimitOffsetPagination
        permission_classes = (AllowAny,)

我如何在此处切换基于序列化程序类 def get_serializer_class(self,): if self.request.query_params.get("player", None): return MyBrokerUserSerialzers

4

2 回答 2

1

在我看来,目前尚不清楚您要达到的目标以及为什么要这样做。

让我把它放在透视图中,如果你有 3 个独立的对象,为它们创建 3 个独立的后端,你不需要其他任何东西。

class UserMixin(object):

    def create(self, validated_data):
        user = MyUser(email=validated_data.pop('email'))
        user.set_password(validated_data.pop('password')
        user.save()  # now you can use user in relations
        validated_data['user'] = user

        super(UserMixin, self).create(**validated_data)

        return user

class PlayerSerializer(serializers.ModelSerializer, UserMixin): 

    class Meta:
        model = Player
        fields = ('id', 'email', 'password', 'contact_name', 'contact_email',
                  'address')
        read_only_fields = ('id',)
        extra_kwargs = {'password': {'write_only': True}}


class ManagerSerializer(serializers.ModelSerializer, UserMixin):

    class Meta:
        model = Manager
        fields = ('id', 'email', 'password', 'contact_name', 'contact_email', 
                  'address', 'city', 'country')
        read_only_fields = ('id',)
        extra_kwargs = {'password': {'write_only': True}}


class CoachSerializer(serializers.ModelSerializer, UserMixin):

    class Meta:
        model = Shipper
        fields = ('id', 'email', 'password', 'contact_name', 'contact_email',       
                  'address', 'city', 'about', 'country',)
        read_only_fields = ('id',)
        extra_kwargs = {'password': {'write_only': True}}

# now 3 viewsets
class PlayerViewset(viewsets.ModelViewSet):
    model = Player
    queryset = Player.objects.all()
    serializer_class = PlayerSerializer

class ManagerViewset(viewsets.ModelViewSet):
    model = Manager
    queryset = Manager.objects.all()
    serializer_class = ManagerSerializer

class CoachViewset(viewsets.ModelViewSet):
    model = Shipper
    queryset = Shipper.objects.all()
    serializer_class = CoachSerializer

# register api ends
api_router.register('player', PlayerViewset)
api_router.register('manager', ManagerViewset)
api_router.register('coach', CoachViewset)

简单,有效,工作量不大...

ps 类名以大写字母开头 - 请阅读 pep-8

于 2016-06-05T01:09:57.707 回答
1

文档中,您可以指定serializer_class告诉您想要的正确序列化程序的属性。

然后,当您继承许多混合类时,您可以覆盖它们的方法并从前端获取信息。对于每种请求方法,您都必须以不同的方式获取前端信息。

class MyUserViewSet(mixins.CreateModelMixin,
                        mixins.RetrieveModelMixin,
                        mixins.DestroyModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.ListModelMixin,
                        GenericViewSet):
    queryset = MyUser.objects.all()
    pagination_class = LimitOffsetPagination
    permission_classes = (AllowAny,)

    def define_serializer_class(self, serializer_class_name):
        serializer_class = serializer_class_name

    def get(self, request, *args, **kwargs):
        #here in GET METHOD you wil user the RetrieveModelMixin
        #So get the kind of serializer from you get params in request.GET["param name"] 
        #and set the right one with a 'if' condition and calling
        # self.define_serializer_class(<the name of the right serializer class>)
        return self.retrieve(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        #here in POST METHOD you wil user the CreateModelMixin
        #So get the kind of serializer from you post playload in request.POST["param name"]
        #and set the right one with a 'if' condition and calling
        # self.define_serializer_class(<the name of the right serializer class>)
        return self.update(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        #Do the same here get the info from the frontend
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        #Do the same here get the info from the frontend
        return self.destroy(request, *args, **kwargs)

很抱歉,我无法告诉正确的代码来执行您想要的操作,但代码中的注释逐步解释了解决您问题的方法。我自己从来没有做过,因为我不喜欢使用混合(它们构成了一切),但它会为你工作。只需找到正确的方法从前端获取 mixins 使用的每种 HTTP 方法的信息,并serializer_class按照我上面所说的进行设置。

我希望它对你有帮助。

于 2016-06-01T04:30:47.433 回答