mongoengine query a list of embedded documents

非 Y 不嫁゛ 提交于 2019-12-06 05:12:41

As the comments are contained with the document then comments will always contain all comments.

Add a property to Post that filters and only returns a list of approved comments eg:

@property
def approved_comments(self):
    return [comment for comment in self.comments if comment.approved]

Try this in your models:

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

class Post(Document):
    id = StringField(required=True, unique=True)
    comments = EmbeddedDocumentListField(Comment)

NOTICE: EmbeddedDocumentListField instead ListField

Then your query in this way

comments_approved =  Post.objects.get(pk=post_id).comments.filter(approve=True)

I Hope help you!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!