Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning id value after object creation with django-rest-framework

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!

like image 693
kahlo Avatar asked Sep 15 '13 17:09

kahlo


1 Answers

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.

like image 198
Navneet Avatar answered Sep 28 '22 02:09

Navneet