我正在发送一个 API 发布请求,请求正文中包含以下内容,以将其序列化为 EventSerializer 文档,而所有者则作为嵌入式文档列表持久保存:
{
"name": "string",
"name_english": "string",
"starts_on": "2020-05-21T18:46:05.049Z",
"ends_on": "2020-05-21T18:46:05.049Z",
"local": "string",
"description": "string",
"owners": [
{
"first_name": "string",
"last_name": "string",
"email": "user@example.com",
"id": "5ec6dd64d581f76fbfad60eb"
}
]
}
模型.py:
class UserRef(EmbeddedDocument):
id = fields.ReferenceField(User, required=True)
first_name = fields.StringField(max_length=255, required=True)
last_name = fields.StringField(max_length=255, required=True)
email = fields.EmailField(max_length=255, required=True)
class Event(Document):
name = fields.StringField(max_length=255, required=True)
name_english = fields.StringField(max_length=255, required=True)
starts_on = fields.DateTimeField(required=True)
ends_on = fields.DateTimeField(required=True)
local = fields.StringField(max_length=255, required=True)
description = fields.StringField(max_length=255, required=True)
owners = fields.EmbeddedDocumentListField(UserRef, required=False)
序列化程序.py:
class UserRefSerializer(serializers.EmbeddedDocumentSerializer):
class Meta:
model = UserRef
class EventSerializer(serializers.DocumentSerializer):
owners = UserRefSerializer(many=True)
class Meta:
ref_name = "Event"
model = Event
fields = ["id", "name", "name_english", "starts_on", "ends_on", "local", "description", "owners"]
def create(self, validated_data):
owners_data = validated_data.pop("owners")
event = Event.objects.create(**validated_data)
event.owners = []
for owner_data in owners_data:
event.owners.append(owner_data)
event.save()
return event
视图.py:
class EventViewSet(viewsets.ModelViewSet):
queryset = Event.objects.all()
serializer_class = EventSerializer
当我运行 post 请求时,Event 对象确实被持久化了;但是,所有者列表(嵌入文档的列表)不会保留在事件中。它只是设置为一个空白列表 [ ]。我在这里做错了什么?