保存时,序列化程序不会返回所有字段

时间:2019-12-10 07:46:58

标签: django django-rest-framework

我有以下序列化器:

class ClientSerializer(serializers.ModelSerializer):
    projects_count = serializers.ReadOnlyField()
    currency = CurrencySerializer(read_only=True)

    class Meta:
        model = Client
        fields = ('id', 'owner', 'name', 'icon_color', 'projects_count', 'hourly_rate', 'currency', )

    def get_projects_count(self, obj):
        if hasattr(obj, 'projects_count'):
            return obj.projects_count
        return 0

这是获取和创建Client对象的视图:

class ClientListView(APIView):
    http_method_names = ['get', 'post']
    authentication_classes = (authentication.SessionAuthentication, )
    permission_classes = [IsAuthenticated]

    def post(self, request, format=None):
        serializer = ClientSerializer(
            context=dict(request=request),
            data=request.data
        )

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request, format=None):
        qs_clients = Client.objects.filter(
            owner=request.user,
        ).annotate(
            projects_count=Count('project'),
        )
        client_serializer = ClientSerializer(
            qs_clients,
            many=True,
        )
        data = dict(
            clients=client_serializer.data,
        )
        return Response(
            data,
            status=status.HTTP_200_OK,
        )

调用POST时,返回的数据不包含project_count字段:

POST:

{"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","hourly_rate":null,"currency":null}

但是对于GET,一切正常:

GET:

{"clients":[{"id":9,"owner":1,"name":"zzz xxx","icon_color":"a45ac8","projects_count":0,"hourly_rate":null,"currency":null}]}

我需要在POST响应中包含projects_count。为什么会丢失?

谢谢!

1 个答案:

答案 0 :(得分:1)

serializers.ReadOnlyField()的接口尝试使用已经是只读字段的serializers.SerializerMethodField()

class ClientSerializer(serializers.ModelSerializer):
    projects_count = serializers.SerializerMethodField()
    #                             ^^^^^^^^^^
    currency = CurrencySerializer(read_only=True)

    class Meta:
        model = Client
        fields = ('id', 'owner', 'name', 'icon_color', 'projects_count', 'hourly_rate', 'currency', )

    def get_projects_count(self, obj):
        if hasattr(obj, 'projects_count'):
            return obj.projects_count
        return 0