从App Engine中的ReferenceProperty获取Key / id [英] Fetching just the Key/id from a ReferenceProperty in App Engine

查看:96
本文介绍了从App Engine中的ReferenceProperty获取Key / id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



通过使用[Python] API,我可以从文档中创建如下示例的关系:

  class Author(db.Model):
name = db.StringProperty()
$ b $ 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的值是一个键


这让我认为我只能在引用的值上调用.id()。但它也表示:
$ b


ReferenceProperty模型为Key属性值提供了诸如自动解引用的功能。


找不到任何解释何时发生这种引用的情况?

安全地调用.id( )的ReferenceProperty的值?

可以假定调用.id()不会导致数据存储区查找?

解决方案

为了帮助其他搜索者回答我自己的问题...

怀疑调用story.author.key().id()或者甚至story.author.id()将导致数据存储查询。 API文档规定的正确方法是:

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


I could use a little help in AppEngine land...

Using the [Python] API I create relationships like this example from the docs:

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

As I understand it, that example will make two datastore queries. One to fetch the Story and then one to deference the Author inorder to access the name. But I want to be able to fetch the id, so do something like:

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

I want to just get the id from the reference. I do not want to have to deference (therefore query the datastore) the ReferenceProperty value.

From reading the documentation it says that

the value of a ReferenceProperty is a Key

Which leads me to think that I could just call .id() on the reference's value. But it also says:

The ReferenceProperty model provides features for Key property values such as automatic dereferencing.

I can't find anything that explains when this referencing takes place?
Is it safe to call .id() on the ReferenceProperty's value?
Can it be assumed that calling .id() will not cause a datastore lookup?

解决方案

Answering my own question for the sake of helping fellow searchers...

As suspected calling story.author.key().id() or even story.author.id() will result in datastore queries. The correct method dictated by the API docs is:

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

这篇关于从App Engine中的ReferenceProperty获取Key / id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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