I made article system with python flask.
To communicate with mongodb, use flask_mongoengine
Here is my model.
class SubComment(EmbeddedDocument):
no = SequenceField()
body = StringField()
class Comment(EmbeddedDocument):
no = SequenceField()
body = StringField()
sub_comment = ListField(EmbeddedDocumentField(SubComment))
class Article(Document):
title = StringField()
body = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
SubComment
model stored into Comment
model and Comment
model stored into Article
model.
So, this is the output that I want.
{
"_id" : ObjectId("5c0641d81b48d9fe50dfdd7f"),
"title" : "test",
"body" : "gogo",
"comments" : [
{
"no" : 1,
"body" : "first comment",
"sub_comment" : [
{
"no": 1,
"body": "sub comm"
}
]
}
]
}
When I insert Comment
model to Article
model, just use below code.
comment = Comment(
body='first comment'
)
article = Article.objects(body='gogo').first()
article.comments.append(comment)
article.save()
But when I try to insert SubComment
to Comment
, it throw errors -> AttributeError: 'BaseList' object has no attribute 'sub_comment'
Below is the code I used.
comment = SubComment(
body='sub comment'
)
article = Article.objects(title='test', comments__no=1).first()
article.comments.sub_comment.append(comment)
article.save()
After some searched, people said there is no way to insert nested field.
Is there any solution here? I have to use raw query?
Thanks!