I'm in a situation where I have a endpoint samples
which represents a model sample
via a ModelViewSet
.
My goal is, that when a user POST's against this endpoint with data
like
{
"a":1,
"b":2 ,
"c":3
}
i want to be able to override/add key:value pairs to this incoming payload stored in request.data
within the create
method.
This can not be done by simply accessing request.data
since it's a QueryDict
which is immutable.
Furthermore i can not achieve this in the perform_create()
method since the data i might inject is validation-critical.
Currently I'm stuck with the following solution which requires me to REWRITE the complete create()
method :
class MyViewSet(viewsets.ModelViewSet):
queryset = Sample.objects.all()
serializer_class = MSampleSerializer
name = "samples"
def add_info(self, request):
...
<acquire_info>
...
data = request.data.dict()
data["s"] = <info1>
data["r"] = <info1>
data["t"] = <info1>
return data
def create(self, request, *args, **kwargs):
data = self.add_info(request)
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
Is there a generic way to edit the
request.data
before any action method, likecreate()
orput()
, is called ?If not 1.); is there a different possibility ?
Thanks in advance.