I tried the solution for the serializer, but there seemed to be an exception before it turned on the create(self, validated_data) serializer function. This is because I use ModelViewSet (which in turn uses the class CreatedModelMixin ). Further studies show that the exception here is:
rest_framework/mixins.py class CreateModelMixin(object): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) <== Here
Since I want to keep all the functions provided by the framework, I prefer to catch exceptions and use the route to update:
from rest_framework.exceptions import ValidationError class MyViewSet(viewsets.ModelViewSet) def create(self, request, *args, **kwargs): pk_field = 'uuid' try: response = super().create(request, args, kwargs) except ValidationError as e: codes = e.get_codes()
My application can always call POST /api/my_model/ with parameters (here uuid = primary key).
However, it would be better if we could handle this in the update function?
def update(self, request, *args, **kwargs): try: response = super().update(request, *args, **kwargs) except Http404: mutable = request.data._mutable request.data._mutable = True request.data["uuid"] = kwargs["pk"] request.data._mutable = mutable return super().create(request, *args, **kwargs) return response
source share