Pwntifex
Pwntifex

Reputation: 85

Google App Engine: Does calling .key().id() on a reference property trigger a get of that entity?

If I have an object with a reference property, will calling the .key() or .key().id() method on the reference property cause it to be retrieved from the data store? Or can I can I get the value from those without a request being triggered?

class MyObject(db.Model):
    reference = db.ReferenceProperty()

myObj = MyObject( reference = myOtherObject )
myObj.put()

# Will this retrieve the key without doing a get for the object?
temp1 = myObj.reference.key()

# What about this?
temp2 = myObj.reference.key().id()

Upvotes: 3

Views: 1145

Answers (2)

moraes
moraes

Reputation: 13629

Accessing the property from the model instance will de-reference it (it will be fetched):

# This will retrieve the key after doing a get for the object.
temp1 = myObj.reference.key()

To get the key without de-referencing, use:

# This will retrieve the key without doing a get for the object.
temp1 = MyObject.reference.get_value_for_datastore(myObj)

# Then you get the id...
temp2 = temp1.id()

Upvotes: 10

fredrik
fredrik

Reputation: 17617

Yes. Accessing a always trigger a ReferenceProperty sub-query.

I usually store two more properties when using ReferenceProperty. When saving the reference model i also store a string representative of the key and a int of the id.

class MyObject(db.Model):
    reference = db.ReferenceProperty()
    referenceStrKey = db.StringProperty()
    referenceId = db.IntProperty()

Lately I only store the key as a string and then ad to properties:

class MyObject(db.Model):
    referenceStrKey = db.StringProperty()

    @property
    def reference(self):
        return RefModel.get(db.Key(self.referenceStrKey))

    @property
    def referenceId(self):
        return db.Key(self.referenceStrKey).id()

Upvotes: 0

Related Questions