mongoengine查询嵌入文档列表

Tri*_*ews 3 mongodb mongoengine

我遇到了一个经典的陷阱,但找不到我应该做的mongoengine的好例子.

使用标准的博客示例我有类似的东西:

class Comment(EmbeddedDocument):
    author = StringField()
    approved = BooleanField(default=False)

class Post(Document):
    id = StringField(required=True, unique=True)
    comments = ListField(EmbeddedDocumentField(Comment))
Run Code Online (Sandbox Code Playgroud)

对于给定的博客帖子(带有id some_id),我只想加载已批准的评论列表.如果帖子的任何评论被批准,我会不小心加载所有评论,因为我匹配列表中的元素.

小智 10

在您的模型中试试这个:

class Comment(EmbeddedDocument):
    author = StringField()
    approved = BooleanField(default=False)

class Post(Document):
    id = StringField(required=True, unique=True)
    comments = EmbeddedDocumentListField(Comment)
Run Code Online (Sandbox Code Playgroud)

注意:EmbeddedDocumentListField代替ListField

然后以这种方式查询

comments_approved =  Post.objects.get(pk=post_id).comments.filter(approve=True)
Run Code Online (Sandbox Code Playgroud)

我希望能帮到你!


Ros*_*oss 5

由于评论包含在文档中,因此评论将始终包含所有评论.

添加一个属性到Post过滤器,只返回已批准的注释列表,例如:

@property
def approved_comments(self):
    return [comment for comment in self.comments if comment.approved]
Run Code Online (Sandbox Code Playgroud)