mongoengine查询嵌入式文档列表 [英] mongoengine query a list of embedded documents

查看:144
本文介绍了mongoengine查询嵌入式文档列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个典型的陷阱,但是在mongoengine上找不到我应该做的很好的例子.

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

对于给定博客帖子(ID为some_id),我只想加载已批准评论的列表.如果帖子的任何评论被批准,我会不小心加载所有评论,因为我匹配列表中的一个元素.

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.

推荐答案

注释包含在文档中,因此注释将始终包含所有注释.

As the comments are contained with the document then comments will always contain all comments.

在Post中添加一个属性,该属性会过滤并仅返回已批准评论的列表,例如:

Add a property to Post that filters and only returns a list of approved comments eg:

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

这篇关于mongoengine查询嵌入式文档列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆