0

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!

Hide
  • 3,199
  • 7
  • 41
  • 83

1 Answers1

0

[SOLVED]

I solved with for loop like this.

count = 0
article = Article.objects(title='test', comments__no=1).first()
for comment in article.comments:
    if comment.no == 1:
        print(comment.no)
        count = comment.no - 1

article.comments[count].sub_comment.append(sub_comment)
article.save()

But I don't know it is the right way.

If you have any other solution, please comment it.

Hide
  • 3,199
  • 7
  • 41
  • 83