python-3.xgoogle-cloud-datastoreapp-engine-ndbgoogle-app-engine-python

Is there a pattern for declaring a computed key for a model?


I'd like a particular ndb.Model key's string id to be automatically set to the concatenation of two of the models' properties. These two properties are write-once, although other properties might change. This approach helps ensure that the entities are unique for these two properties.

Here's how the class might look like:

class Foo(ndb.Model):
  bar: ndb.StringProperty()
  baz: ndb.StringProperty()

An entity could be constructed like this:

foo = Foo(id='bar-baz', bar='bar', baz='baz')
foo.put()

Is there a pattern to automatically set that id in the model class itself, similar to a ComputedProperty?


Solution

  • You can use the _pre_put_hook function to set the key name as part of a put. This would also be the place to verify that bar & baz do not change as part of an update.