代码之家  ›  专栏  ›  技术社区  ›  Hide

mongoengine对嵌套listfield的查询

  •  0
  • Hide  · 技术社区  · 6 年前

    我用python flask制作了文章系统。

    要与mongodb通信,请使用 flask_mongoengine

    这是我的模型。

    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 模型存储到 Comment 模型与 议论 模型存储到 Article

    这就是我想要的输出。

    {
        "_id" : ObjectId("5c0641d81b48d9fe50dfdd7f"),
        "title" : "test",
        "body" : "gogo",
        "comments" : [
            {
                "no" : 1,
                "body" : "first comment",
                "sub_comment" : [
                       {
                            "no": 1,
                            "body": "sub comm"
                       }
                ]
            }
        ]
    }
    

    当我插入 议论 文章 模型,只需使用下面的代码。

    comment = Comment(
        body='first comment'
    )
    article = Article.objects(body='gogo').first()
    article.comments.append(comment)
    article.save()
    

    小组委员会 议论 ,它会抛出错误-> AttributeError: 'BaseList' object has no attribute 'sub_comment'

    下面是我使用的代码。

    comment = SubComment(
        body='sub comment'
    )
    article = Article.objects(title='test', comments__no=1).first()
    article.comments.sub_comment.append(comment)
    article.save()
    

    这里有什么解决办法吗?我必须使用原始查询?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   Hide    6 年前

    [已解决]

    我解决了这个问题 for 像这样循环。

    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()
    

    但我不知道这是正确的方法。

    如果您有任何其他解决方案,请予以评论。