首页 > 解决方案 > 如何将文件内容传递给序列化程序?

问题描述

我是 django 的新手。我需要实现两个 POST 选项;一个来自 url 参数,另一个来自文件数据。

例如,curl -X POST localhost:8000/api/test?key=valuecurl -X POST -F "file=@myfile.json" localhost:8000/api/test

我在下面进行了测试,但失败了。

class TestEntryView(ListCreateAPIView):
    queryset = TestEntry.objects.all().order_by('-id')
    parser_classes = (MultiPartParser, FormParser,)
    serializer_class = TestEntrySerializer

    def perform_create(self, serializer):
        if self.request.FILES.get('file'):
            file_obj = request.FILES['file']
            filename = '/api/mytest/.temp/testfile'
            with open(filename, 'wb+') as temp_file:
                for chunk in file_obj.chunks():
                    temp_file.write(chunk)
            with open(filename, 'r') as temp_file:
                data = json.load(temp_file)
                serializer.save(**data)
        serializer.save()

=>perform_create()由于验证字段失败而没有被调用。有没有为此目的推荐的方法?

标签: djangodjango-rest-framework

解决方案


推荐阅读