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

Posted by ozone on Stack Overflow See other posts from Stack Overflow or by ozone
Published on 2010-06-15T09:53:27Z Indexed on 2010/06/15 10:22 UTC
Read the original article Hit count: 253

Hi SO, 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?

© Stack Overflow or respective owner

Related posts about python

Related posts about google-app-engine