我使用了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',
)
这样的工作流程。
将图像上传到s3
获取s3路径
将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}
我的代码有错误吗?
谢谢。
答案 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)