0

我对架构中的反向相关对象有疑问。

序列化器:

class MessageSerializer(serializers.ModelSerializer):
    files = FileUploadSerializer(many=True, required=False)

    class Meta:
        model = Message
        fields = ['id', 'sender', 'recipient', 'text', 'is_feedback', 'files']
        read_only_fields = ['sender']

    def create(self, validated_data):
        files = validated_data.pop('files')
        message = Message.objects.create(**validated_data)
        for file in files:
            File.objects.create(message=message, file=file)
        return message

class FileUploadSerializer(serializers.ModelSerializer):  # noqa
    file_uploaded = fields.FileField()

    class Meta:
        model = File
        fields = ['file_uploaded', 'message']
        read_only_fields = ['message']

视图尚未准备好,因为我无法上传文件:

class MessageList(ViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer
    permission_classes = (IsAuthenticated,)
    parser_classes = [MultiPartParser]

    def list(self, request):...

    def create(self, request):
        """Create a new message where sender is current User and recipient is target User."""

        files = request.data.get('files', None)
        print(files)

        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            serializer.save(sender=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

主要问题是这个反向相关的对象(文件)被渲染错误。

图片

而不是某种文件输入数组,我得到了 json 数组。我应该怎么做才能修复它?我知道我可以用另一种方式制作它,比如只制作 files = serializer.ListField(child=FileField...) 并保存这些文件,即使没有任何序列化程序,但我想以某种正确的方式做到这一点 =/

4

0 回答 0