Bruce
Bruce

Reputation: 1380

Serializer does not return all fields when saving

I have following serializer:

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

And this is the view for getting and creating Client objects:

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,
        )

When calling POST, data returned does not contain project_count field:

POST:

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

But for GET, there is everything ok:

GET:

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

I need to have projects_count included in the POST response. Why is it missing?

Thanks!

Upvotes: 0

Views: 602

Answers (1)

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

Intead of serializers.ReadOnlyField() try to use serializers.SerializerMethodField() which is already a read-only field

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

Upvotes: 1

Related Questions