Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoengine query a list of embedded documents

I'm running into a classic pitfall, but can't find a good example with mongoengine of what I should be doing.

Using the 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 a given blog post (with id some_id) I just want to load the list of approved comments. I keep accidentally loading all comments if any of the comments for the post are approved, because I'm matching an element of the list.

like image 435
TristanMatthews Avatar asked Dec 02 '22 16:12

TristanMatthews


1 Answers

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!

like image 186
leocoder Avatar answered Dec 09 '22 10:12

leocoder