Search code examples
pythondjangodjango-rest-frameworkdjango-rest-viewsets

Overwrite django rest response for return only pk


I'm trying to overwrite the response that is sended by django when create a new object.

I need to return only the primary key of the created object instead the whole object.

The function that I'm trying to overwrite is this:

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    data = serializer.data
    print(data['id'])
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Where the name of the field "id' inside the data object can be different by each entity.

The final code should be something like:

return Response(pk, status=status.HTTP_201_CREATED, headers=headers)

Any idea about how can I make it work?

Thanks in advance


Solution

  • The data that a Response expects is a dict, so:

    def create(self, request, *args, **kwargs):
        ...
    
        return Response(
            {"pk": serializer.data["id"]},
            status=status.HTTP_201_CREATED,
            headers=headers,
        )
    

    Alternatively:

    Instead of using .perform_create, call .save directly. Catch the instance and use its .pk:

    def create(self, request, *args, **kwargs):
        ...
        # self.perform_create(serializer)
        instance = serializer.save()
        return Response(
            {"pk": instance.pk},
            status=status.HTTP_201_CREATED,
            headers=headers,
        )