Search code examples
google-app-enginegoogle-cloud-datastorereferenceproperty

How to set a ReferenceProperty using only a Key, not getting the Model


I want to be able to, given the key to a model in the datastore, simply set the referenceproperty without loading the model itself (as I don't need that information).

For example:

class Book(db.Model):
    author = db.StringProperty()
    title = db.StringProperty()

class Review(db.Model):
    book = db.ReferenceProperty(Book)
    description = db.StringProperty()

Assuming that I already have the key to a Book (call it bookKey), but I don't have the corresponding Book object itself, is there a way to do the equivalent of

review = Review()
review.description = "It was ok, but I would recommend it for insomniacs."
review.book = bookKey

or do I need to

book = Book.get(bookKey) #I don't want this datastore access
                         #as I don't need the book object.
review = Review()
review.description = "It was ok, but I would recommend it for insomniacs."
review.book = book

I've found the way to extract the key and ID from the ReferenceProperty using get_value_for_datastore, but I'm after a "set".


Solution

  • review.book = bookKey will work just fine, and set the referenceproperty without fetching the model.