Issue
This Content is from Stack Overflow. Question asked by aroooo
We have a modelViewset:
class ObjectViewSet(viewsets.ModelViewSet):
serializer_class = MyObjectSerializer
def perform_create(self, serializer):
...
def perform_update(self, serializer):
...
def perform_destroy(self, instance):
...
But perform_create doesn’t return the newly created object which means the 201 response only contains a few random fields that were specified during creation and not the whole new object.
Is there some special way to get the object without overriding the .create() call? It seems like returning the new object is expected behavior, so I’m worried I’m doing something wrong here.
Solution
It’s a viewset, it needs to return HTTP response to client, from the link you posted you can access it via serializer.instance:
You can access the object through serializer.instance
But you have to process the request and create the instance first:
def perform_create(self, serializer):
# call parent class implementation to create the instance
response = super().perform_create(serializer)
# now you can access it via serializer
instance = serializer.instance
# return the response to the client
return response
This Question was asked in StackOverflow by aroooo and Answered by Đào Minh Hạt It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.