1👍
Depending on the type of view you are using, you can either:
- manually build the
Response
so that it includes the newly created resource. - rely on
create(request, *args, **kwargs)
provided byCreateModelMixin
I think the easiest way to achieve what you are looking for is to use the CreateAPIView
. According to the documentation,
If an object is created this returns a 201 Created response, with a
serialized representation of the object as the body of the response.
If the representation contains a key named url, then the Location
header of the response will be populated with that value.
So this generic view for sure returns the data in the body of each response, but if you are interested in getting a url for each of your resources, you should probably take a look at HyperlinkedModelSerializer. Those serializers work basically like the ModelSerializer
except that they include a url
field in the representation of each object, allowing you to browse through the resources.
Also if you are only interested in getting the id/pk
of each created object, I think ModelSerializer
sets an id
field by default for each representation that corresponds to the actual pk
in the database. Not sure of that, but if it is not the case you can still explicitly ask for it by specifying the fields to be serialized, namely
class MySerializer(ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'name', 'color',)