googleappengine Python数据存储:条件数据库引用属性()

2024-03-29 08:53:22 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有两个模型:作者和帖子。两者都有一个布尔字段“status”。文章由作者完成,所以数据库引用属性()字段。模型如下:

class Authors(db.Model):
    status = db.BooleanProperty(default = True)
    name = db.StringProperty(required = True)

class Posts(db.Model):
    status = db.BooleanProperty(default = True)
    title = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    author = db.ReferenceProperty(Authors)

所以,我希望当两个状态字段(帖子和引用的作者)都设置为True时,能够在我的站点上列出帖子。如果我设置作者身份如果设置为False,将自动不再显示其所有子帖子。你知道吗

我知道这行不通,但应该是这样的:

q = Posts.all()
q.filter('status =', True)
q.filter('author.status =', True)
q.run()

我知道这是一个连接,而GAE数据存储不支持连接,但是我怎么可能做到这一点呢?提前谢谢。你知道吗


Tags: 模型truedefaultdbmodelstatusrequired作者
1条回答
网友
1楼 · 发布于 2024-03-29 08:53:22

正如您所说,您不能与数据存储进行连接。所以你只能反复检查状态。你知道吗

具体的方法取决于你的数据。您可能希望先查询作者,然后获取每个状态正确的作者的帖子:

all_posts = []
q = Authors.all().filter('status', True)
for author in q:
    posts = Post.all().filter('author', author).filter('status', True)
    all_posts.extend(posts.run())

另一种方法是获取status=True的所有作者的密钥,将它们放入一个集合中,然后遍历所有文章并检查author密钥是否存在:

all_posts = []
authors = set(Authors.all(keys_only=True).filter('status', True).run())
q = Post.all().filter('status', True)
for post in q:
    if post._author in authors:
        all_posts.append(post)

就像我说的,哪个更有效取决于你有多少不同的作者,每个人有多少篇文章,以及每个人的状态分布。试试它们,检查生成了多少个查询。你知道吗

相关问题 更多 >