[Solved]-Returning id value after object creation with django-rest-framework

1👍

Here, DetectorSerializer inherits from ModelSerializer as well as your view inherits from generics ListCreateAPIView so when a POST request is made to the view, it should return the id as well as all the attributes defined in the fields of the Serializer.

1👍

Because it took me a few minutes to parse this answer when I had the same problem, I thought I’d summarize for posterity:

The generic view ListCreateApiView does return the created object.

This is also clear from the documentation listcreateapiview: the view extends createmodelmixin, which states:

If an object is created this returns a 201 Created response, with a serialized representation of the object as the body of the response.

So if you have this problem take a closer look at your client side!

post$.pipe(tap(res => console.log(res)))

should print the newly created object (assuming rxjs6 and ES6 syntax)

0👍

As mentioned above, To retrieve the id for the new created object, We need to override the post method, find the the update code for more details:

class DetectorAPIList(generics.ListCreateAPIView):
    serializer_class = DetectorSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    parser_classes = (MultiPartParser, FileUploadParser,)

        def post(self, request, format=None):
        serializer = DetectorSerializer(data=request.data)
        if serializer.is_valid():
            obj = serializer.save()
            return Response(obj.id, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Leave a comment