Return id value after creating an object using django-rest-framework

I use the generic django-rest-framework views to create objects in a model through a POST request. I would like to know how to return the identifier of an object created after POST or more general, any additional information about the created object.

This is a view class that creates (and lists) an 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')) 

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!

+7
python post django django-rest-framework
source share
2 answers

Here, the DetectorSerializer inherits from ModelSerializer , and your view inherits from the generic ListCreateAPIView , so when a POST request is made for the view, it should return the identifier, as well as all the attributes defined in the Serializer fields.

0
source share

Since it took me a few minutes to parse this answer when I had the same problem, I decided to summarize for posterity:

The generic ListCreateApiView returns the created object.

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

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

So if you have this problem, take a look at the customer!

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

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

0
source share

All Articles