【问题标题】:Retrieving hierarchial data from datastore从数据存储中检索分层数据
【发布时间】:2010-10-28 10:31:52
【问题描述】:

我正在使用 Google App Engine(和 Python)构建应用。我有两个关于从数据存储区检索数据的问题。

我有关于用户的信息和关于用户发布的帖子的信息。这是 DB 模型的一部分:

class User(db.Model):
    country = db.StringProperty() 
    # many other entities

class Post(db.Model):
    author = db.ReferenceProperty(User) 
    # many other entities

我想检索某个国家/地区的用户发布的帖子。我是这样尝试的:

posts_query = Post.all().filter(' author.country == ', country)
posts = posts_query.fetch(limit = 100)

但此查询不返回任何结果(国家/地区变量的值存在于数据存储中)。我需要在我的查询中更正什么,这样才能正常工作?

第二个问题:如果帖子数未知(并且可能 > 100),我如何(在给定情况下)从数据存储中检索所有帖子?

提前致谢,

-skazy

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore


    【解决方案1】:

    如果您想这样做,您需要进行非规范化:在用户的所有帖子中存储用户国家/地区的副本,然后对其进行查询。数据存储不支持连接,这是满足此查询所必需的,并且在任何情况下,非规范化都会更有效。

    就检索“所有”结果而言,您可以指定一个任意大的限制,但请考虑:您真的要这样做吗?您一次可以明智地向用户展示多少个结果是有限制的;如果你有更多的结果,你几乎肯定想要分页,而不是。

    【讨论】:

      【解决方案2】:

      二次非规范化。如果国家/地区是您需要经常查询的特定事物,您可以为其添加一个新模型。 Country 然后成为用户和 Post 的 ReferenceProperty:

      class User(db.Model):
        country = db.ReferenceProperty(Country,collection_name=users) 
        # many other entities
      
      class Post(db.Model):
        author = db.ReferenceProperty(User) 
        country = db.ReferenceProperty(Country,collection_name=posts) 
        # many other entities
      
      class Country(db.Model):
        name = db.StringProperty()
      
      # posts from everyone in the user's country:
      # user.country.posts.all()
      

      在回答您的第二个问题时,您可以使用您的 posts_query 作为可迭代对象来检索所有结果。请参阅 App Engine 文档:http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_fetch

      【讨论】:

        猜你喜欢
        • 2021-09-02
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多