get_value_for_datastore() example

When using a db.ReferenceProperty in google app engine, the function get_value_for_datastore() can be used to get the key of a referenced datastore model without causing GAE to automatically fetch the model – this can be very handy if you are trying to optimise the performance of your cloud code.

 

from google.appengine.ext import db
class A(db.Model):
    b = db.ReferenceProperty(B)
class B(db.Model):
    name = db.StringProperty()
 

In the above code, A contains a reference to B, given a model of type A, b’s key can be retrieved as follows:

 

a = A().get_by_id(1234354)
b_key = A.b.get_value_for_datastore(a)
 

This will get b’s key without fetching its model!