Fetching just the Key/id from a ReferenceProperty

2019-03-09 21:31发布

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条回答
Deceive 欺骗
2楼-- · 2019-03-09 22:01

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()
查看更多
登录 后发表回答