MongoEngine中嵌套嵌入文档的验证错误

2024-05-23 19:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建两个级别的嵌套嵌入文档(嵌入文档中的嵌入文档)

代码如下:

from mongoengine import *

class CommentDetails(EmbeddedDocument):
    name = StringField()
    category = StringField()

class Comment(EmbeddedDocument):
    content = StringField()
    comments = ListField(EmbeddedDocumentField(CommentDetails))

class Page(Document):
    comments = ListField(EmbeddedDocumentField(Comment))

comment1 = Comment(content='Good work!',comments=CommentDetails(name='John',category='fashion'))
comment2 = Comment(content='Nice article!',comments=CommentDetails(name='Mike',category='tech'))

page = Page(comments=[comment1, comment2])
page.save()

运行时会出现以下错误:

ValidationError: ValidationError (Page:None) (comments.Only lists and tuples may be used in a list field >1.comments.Only lists and tuples may be used in a list field: ['comments'])

我尝试使用单个嵌套文档,它可以工作,如果我不使用EmbeddedDocuments作为列表,它也可以工作。但不确定为什么它不适用于多层次的嵌入式文档列表


Tags: name文档pagecommentcontentcommentsclasscategory
1条回答
网友
1楼 · 发布于 2024-05-23 19:31:56

问题来自以下两行:

comment1 = Comment(content='Good work!',comments=CommentDetails(name='John',category='fashion'))
comment2 = Comment(content='Nice article!',comments=CommentDetails(name='Mike',category='tech'))

comments应该是一个列表,但您提供了一个对象

使用以下命令:

comment1 = Comment(content='Good work!',comments=[CommentDetails(name='John',category='fashion')])
comment2 = Comment(content='Nice article!',comments=[CommentDetails(name='Mike',category='tech')])

相关问题 更多 >