Refactor UpdateModelMixin.update

Reduce nesting, return early in error cases.
This commit is contained in:
Ian Foote 2014-02-18 12:08:12 +00:00
parent 822eb39599
commit f22aeeb0a3

View File

@ -116,30 +116,27 @@ class UpdateModelMixin(object):
partial = kwargs.pop('partial', False) partial = kwargs.pop('partial', False)
self.object = self.get_object_or_none() self.object = self.get_object_or_none()
if self.object is None:
created = True
save_kwargs = {'force_insert': True}
success_status_code = status.HTTP_201_CREATED
else:
created = False
save_kwargs = {'force_update': True}
success_status_code = status.HTTP_200_OK
serializer = self.get_serializer(self.object, data=request.DATA, serializer = self.get_serializer(self.object, data=request.DATA,
files=request.FILES, partial=partial) files=request.FILES, partial=partial)
if serializer.is_valid(): if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
try: try:
self.pre_save(serializer.object) self.pre_save(serializer.object)
except ValidationError as err: except ValidationError as err:
# full_clean on model instance may be called in pre_save, so we # full_clean on model instance may be called in pre_save, so we
# have to handle eventual errors. # have to handle eventual errors.
return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST) return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
self.object = serializer.save(**save_kwargs)
self.post_save(self.object, created=created)
return Response(serializer.data, status=success_status_code)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if self.object is None:
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
self.object = serializer.save(force_update=True)
self.post_save(self.object, created=False)
return Response(serializer.data, status=status.HTTP_200_OK)
def partial_update(self, request, *args, **kwargs): def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True kwargs['partial'] = True