drf mongoengine序列化程序imagefield none

时间:2019-02-14 01:31:22

标签: django django-rest-framework mongoengine django-serializer

我使用了Django restframework和mongoengine。

这是我的模型和序列化器。

[model.py]

class Attachment(EmbeddedDocument):
    attachment_id = SequenceField()
    path = StringField()
    path_small = StringField()

class Book(Document):
    book_id = SequenceField()
    user_id = LongField(required=True)
    attachments = ListField(EmbeddedDocumentField(Attachment))
    created_at = DateTimeField(default=datetime.now().replace(microsecond=0))
    updated_at = DateTimeField(default=datetime.now().replace(microsecond=0))

[serializer.py]

from rest_framework_mongoengine.serializers import DocumentSerializer
from rest_framework.serializers import ImageField
from books.models.mongo import Book

class BookSerializer(DocumentSerializer):
    image = ImageField()
    class Meta:
        model = Appeal
        fields = (
            'book_id',
            'image',
        )

这样的工作流程。

  1. 将图像上传到s3

  2. 获取s3路径

  3. 将s3路径保存到models.py中的attachments字段。

因此请不要在models.py中定义ImageField()的附件。

只需在序列化程序中设置image = ImageField()即可验证其是否为正确的图像。

但是当我使用serializer.is_valid()进行验证时,图像会显示None

[views.py]

class BookList(GenericAPIView):
    serializer_class = BookSerializer
    queryset = ''

    def post(self, request: Request) -> Union[Response, NoReturn]:
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            print(serializer.data)
            appeal = CreateAppealInteractor().execute(request=serializer.data)
            return Response(status=status.HTTP_200_OK)

您知道,在serializer.is_valid()之后,我打印了serializer.data。

但它不会像这样-> {'book_id': 1, 'image': None}

我的代码有错误吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

问题在聊天室中解决。只需使用validated_data

class BookList(GenericAPIView):
    serializer_class = BookSerializer
    queryset = ''

    def post(self, request: Request) -> Union[Response, NoReturn]:
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            appeal = CreateAppealInteractor().execute(request=serializer.validated_data)
            return Response(status=status.HTTP_200_OK)