Reputation: 32949
I am familiar that i can set always_return_data
to True
to have the server return the serialized data back on POST
and PUT
requests. But is there a way i can specifically ask for the data to be returned on a particular POST
call and not all POST/PUT
calls ?
Upvotes: 1
Views: 154
Reputation: 1040
In my opinion best way is to override dehydrate method and set always_return_data=True:
class SomeModelResource(ModelResource):
class Meta:
queryset = SomeModel.objects.all()
always_return_data=True
def dehydrate(self, bundle):
if request.META['REQUEST_METHOD'] == 'POST' and\
request.POST.get('param', None)=='PARAM':
bundle.data = dict(id=bundle.obj.pk,
name=bundle.obj.name)
return bundle
Upvotes: 1
Reputation: 4487
You could set always_return_data
to True
and manually remove all the data from your bundle in either the dehydrate
or the alter_detail_data_to_serialize
method but that would just lead to an empty JSON (or whatever serialization you prefer) object to be returned, which is not exactly an empty response.
The probably most explicit way to the wanted behavior would be to override the <method>_list
and <method>_detail
functions and implement the decision whether to return data or not according to your needs.
Here's an example of post_list
that takes a GET-Parameter named return_data
to decide:
def post_list(self, request, **kwargs):
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(request, deserialized)
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
location = self.get_resource_uri(updated_bundle)
return_data = updated_bundle.request.GET.get('return_data', None)
if not return_data is None:
updated_bundle = self.full_dehydrate(updated_bundle)
updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
else:
return http.HttpCreated(location=location)
Upvotes: 2
Reputation: 1790
I would suggest adding an extra parameter to the post on which you want data returned. If the parameter exists in the post variables add the required data to the bundle in dehydrate
Upvotes: 1