11

I am using django-rest-framework generic views to create objects in a model via POST request. I would like to know how can I return the id of the object created after the POST or more general, any additional information about the created object.

This is the view class that creates (and lists) the object:

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

    def pre_save(self, obj):
        obj.created_by = self.request.user.get_profile()

    def get_queryset(self):
        return (Detector.objects
                .filter(get_allowed_detectors(self.request.user))
                .order_by('-created_at'))

The model serializer:

class DetectorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Detector
        fields = ('id', 'name', 'object_class',
              'created_by', 'public', 'average_image', 'hash_value')
        exclude = ('created_by',)

Thanks!

kahlo
  • 2,314
  • 3
  • 28
  • 37
  • After you created a new object you just need to return the last id present in database. this link might help you. http://stackoverflow.com/questions/2548493/in-python-after-i-insert-into-mysqldb-how-do-i-get-the-id – sawan gupta Sep 15 '13 at 17:38
  • Thank you sawan, but I was looking to achieve this within the django-rest-framework. I would like to know if there is any solution less low level than that one. – kahlo Sep 15 '13 at 17:41
  • I guess if `DetectorSerializer` inherits from `ModelSerializer`, the post method should return created model, can we see `DetectorSerializer`? – mariodev Sep 15 '13 at 18:13
  • @Mingot seems fine to me.. are you saying the response body is empty every time you make POST? – mariodev Sep 15 '13 at 18:31
  • 2
    Thank you very much @mariodev. I apologize, my problem was client side. Although I double check if I received the data, I was doing it wrong. All the data about the created object is sent. Thanks again! – kahlo Sep 15 '13 at 18:55
  • @kahlo you might want to mark this as answered – kdazzle Feb 09 '15 at 05:40
  • @kadzzle, sorry for the question but, how do I do to mark it as answered? – kahlo Feb 10 '15 at 14:10
  • 1
    No problem @kahlo. Just answer the question yourself and then select your answer as the correct one. – kdazzle Feb 22 '15 at 17:46

3 Answers3

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.

Navneet
  • 4,543
  • 1
  • 19
  • 29
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)

D. Veen
  • 358
  • 3
  • 9
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)
Husam Alhwadi
  • 383
  • 3
  • 11