Exemplo n.º 1
0
 def conflict(self, key, **kwargs):
     """
     A helper method that simply raises a validation error.
     """
     try:
         msg = self.error_messages[key]
     except KeyError:
         class_name = self.__class__.__name__
         msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
         raise AssertionError(msg)
     message_string = msg.format(**kwargs)
     raise Conflict(message_string)
 def to_internal_value(self, data):
     """
     Ensure that the given type is one of the expected polymorphic types, then retrieve the
     appropriate polymorphic serializer and use this to handle internal value.
     """
     received_type = data.get('type')
     expected_types = self.get_polymorphic_types()
     if received_type not in expected_types:
         raise Conflict(
             'Incorrect relation type. Expected on of [{expected_types}], '
             'received {received_type}.'.format(
                 expected_types=', '.join(expected_types), received_type=received_type))
     serializer_class = self.get_polymorphic_serializer_for_type(received_type)
     self.__class__ = serializer_class
     return serializer_class(data, context=self.context).to_internal_value(data)
Exemplo n.º 3
0
    def delete(self, request, *args, **kwargs):
        related_instance_or_manager = self.get_related_instance()

        if isinstance(related_instance_or_manager, Manager):
            related_model_class = related_instance_or_manager.model
            serializer = self.get_serializer(data=request.data, model_class=related_model_class, many=True)
            serializer.is_valid(raise_exception=True)
            if frozenset(serializer.validated_data).isdisjoint(frozenset(related_instance_or_manager.all())):
                return Response(status=204)
            try:
                related_instance_or_manager.remove(*serializer.validated_data)
            except AttributeError:
                raise Conflict(
                    'This object cannot be removed from this relationship without being added to another'
                )
        else:
            raise MethodNotAllowed('DELETE')
        result_serializer = self._instantiate_serializer(related_instance_or_manager)
        return Response(result_serializer.data)