Mongoengine requests a list of embedded documents

I run into a classic trap, but can't find a good mongoengine example of what I should do.

Using a standard blog example, I have something like:

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

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

For this blog post (with id some_id), I just want to download a list of approved comments. I accidentally download all comments if any comments on the post are approved, because I am matching the list item.

+3
source share
2 answers

Because comments are contained in the document, comments will always contain all comments.

Add the Publish property, which filters and returns only a list of approved comments, for example:

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

:

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

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

: EmbeddedDocumentListField ListField

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

!

+7

All Articles