Fetching just the Key/id from a ReferenceProperty in App Engine

两盒软妹~` 提交于 2019-12-03 05:57:20

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/3044121/fetching-just-the-key-id-from-a-referenceproperty-in-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!