代码之家  ›  专栏  ›  技术社区  ›  Chris Farmiloe

仅从appengine中的ReferenceProperty获取密钥/id

  •  16
  • Chris Farmiloe  · 技术社区  · 16 年前

    我需要一点帮助。。。

    使用[Python]API,我从文档中创建了如下示例所示的关系:

    class Author(db.Model):
        name = db.StringProperty()
    
    class Story(db.Model):
        author = db.ReferenceProperty(Author)
    
    story = db.get(story_key)
    author_name = story.author.name
    

    据我所知,该示例将进行两个数据存储查询。一个去取回故事,然后一个去尊重作者以便取到名字。但我希望能够获取id,所以请执行以下操作:

    story = db.get(story_key)
    author_id = story.author.key().id()
    

    我想 只是 从引用中获取id。我不希望必须遵从(因此查询数据存储)ReferenceProperty值。

    ReferenceProperty的值是一个键

    ReferenceProperty模型为关键特性值提供了自动取消引用等功能。

    什么时候 这是怎么回事?
    对ReferenceProperty的值调用.id()安全吗?
    是否可以假定调用.id()不会导致数据存储查找?

    1 回复  |  直到 16 年前
        1
  •  27
  •   Chris Farmiloe    16 年前

    调用story.author.key().id()甚至story.author.id()都会导致数据存储查询。正确的方法 dictated by the API docs 是:

    story = db.get(story_key)
    author_id = Story.author.get_value_for_datastore(story).id()