当用户上传一个文档并点击提交时,该文件将被存储在一个文件夹中,并与一堆其他细节沿着创建一个数据库条目。我正在寻找的是,如果文档没有被上传到特定位置,则可以避免保存。
serializer.py
class DocumentSerializer(serializers.ModelSerializer):
class Meta:
model = Request
fields = ['file', 'doc_type']
def create(self, validated_data):
msg = self.__construct_message_body()
validated_data['type'] = Request.request_types[-1][0]
validated_data['input_message'] = msg
instance = ParseRequest.objects.create(**validated_data)
msg['request_id'] = instance.id
instance.input_message = msg
instance.save()
return instance
views.py
class DocumentView(CreateAPIView, ResponseViewMixin):
parser_classes = (MultiPartParser, FileUploadParser,)
serializer_class = DocumentSerializer
def create(self, request, *args, **kwargs):
try:
data = request.data
serializer = self.get_serializer(
data=data, context={'request': request})
serializer.is_valid()
serializer.save()
except Exception as e:
logger.error(e)
return self.error_response(message=ERROR_RESPONSE['UPLOAD_DOCUMENT'])
return self.success_response(message=SUCCESS_RESPONSE['UPLOAD_DOCUMENT'])
1条答案
按热度按时间a5g8bdjr1#
您可以使用原子事务。并且可以按如下方式更改代码:
第一个月
如果
with
块内部发生错误,则不会将其保存到数据库中。