gpt4 book ai didi

django - 如何在 Django REST Framework Mongoengine 中序列化 EmbeddedDocumentListField?

转载 作者:行者123 更新时间:2023-12-03 17:41:06 24 4
gpt4 key购买 nike

我正在发送一个 API post 请求,在请求正文中包含以下内容(转换为 JSON 字符串),以将其序列化为 BookCollection 文档,其中书籍作为嵌入式文档列表持久化:

{
'author': '<author_id>',
'books': [
{
'title': 'Grapes of Wrath',
'note': 'More to be ordered.',
'created': '2016-03-11T17:59:01.054Z'
}
]
}

View .py:
def post(self, request, *args, **kwargs):
serializer = BookCollectionSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

模型.py:
class Book(EmbeddedDocument):
title = StringField(required=True, max_length=50)
note = StringField(required=False, max_length=2000)
created = DateTimeField(required=True,
default=datetime.datetime.now())


class BookCollection(Document):
author = ReferenceField(Author, required=True)
books = EmbeddedDocumentListField(Book, required=False)

序列化程序.py
class BookSerializer(EmbeddedDocumentSerializer):

class Meta:
model = Book
depth = 2


class BookCollectionSerializer(DocumentSerializer):
author = ReferenceField(Author)
books = BookSerializer(Book, many=True)

class Meta:
model = BookCollection
depth = 2

def create(self, validated_data):
books = validated_data.pop('books')
book_collection = BookCollection.objects.create(**validated_data)
book_collection.books = []
for book in books:
book_collection.books.append(book)
book_collection.save()
return book_collection

当我运行 post 请求时,BookCollection 对象确实被持久化了;但是,书籍列表(嵌入文档的列表)并未保留在 BooksCollection 中。它只是设置为一个空白列表 []。我在这里做错了什么?我还尝试从 create() 方法中删除逻辑,但这没有帮助。谢谢!

最佳答案

我发现了问题——这是一个愚蠢的错误。我没有将 API 发布请求内容类型设置为 application/json。一旦我设置了它,它就完美无缺地工作了。

关于django - 如何在 Django REST Framework Mongoengine 中序列化 EmbeddedDocumentListField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36073228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com