Where to alter the response of POST request in Django REST Framework -
i have view inherit createapiview
model serializer set in django rest framework.
when send request, returns json representation of object created.
i wrap data response shown below:
{'data' : { 'field1' : 'value1' , 'field2' : value2 , etc..... } , 'errors' : none , 'message': [{} , {}] , 'result' : 'ok' , }
where best place modify data gets returned?
i tried create custom renderer shown in question: adding root element json response (django-rest-framework) never gets called. because relevant requests rather posts?
i think structure not relevant :
- result : why include field
ok
since status code of request here give information : 200 -> ok, 201 -> created, 400 -> bad request, etc... - data , errors in same response doesn't make sense me. maybe, got special behavior in
created
method of serializer if there error, seems logic there no data send (maybe i'm wrong). drf allow validate data.is_valid()
method, , can send errors (for example)
return response(serializer.errors, status=status.http_400_bad_request)
or directly raise exception .is_valid(raise_exception=true)
.
nevertheless, if wanna keep structure, job can done in view. example :
return response({ 'data': serializer.data, 'errors': serializer.errors, # `.is_valid()` must called 'message': [{} , {}], 'result':'ok' })
Comments
Post a Comment