Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
Chris Farmiloe Avatar asked Jun 15 '10 09:06

Chris Farmiloe


1 Answers

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()
like image 80
Chris Farmiloe Avatar answered Oct 03 '22 22:10

Chris Farmiloe