ModelSerializer的Response中包含的字段

时间:2019-02-27 06:53:19

标签: django-rest-framework

这可能是一个非常简单的问题,但我似乎无法解决。

我有一个像这样的ModelSerializer:

class UserSerializer(serializers.ModelSerializer):
    # http -v POST http://127.0.0.1:8000/user/user-list/ email="f@b.de" password="123"

    def create(self, validated_data):
        user = UserModel.objects.create(
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.is_active = False
        user.save()
        return user


    class Meta:
        model = UserModel
        fields = (
            'email',
            'password',
            'is_active',
            'company',
            'name',
        )
        read_only_fields = ('is_active',)
        extra_kwargs = {
            'password': {'write_only': True},
        }

对应的视图如下:

class UserDetail(APIView):

    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        try:
            user = request.user
            serializer = UserMailSerializer(user)
            print(serializer.data)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except UserModel.DoesNotExist:
            return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED)

当我发送GET请求时,serializer.data将仅返回“电子邮件”地址(我使用的是自定义用户模型,电子邮件为主要标识)。

我想返回所有未指定为write_only的字段。我该如何实现?

1 个答案:

答案 0 :(得分:1)

您在视图中使用 UserMailSerializer 序列化器类,这可能是错误的。使用 UserSerializer 串行器

class UserDetail(APIView):

    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        try:
            user = request.user

            serializer = UserSerializer(user) # change is here <<<<<

            print(serializer.data)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except UserModel.DoesNotExist:
            return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED)