Search code examples
pythongoogle-cloud-datastoredata-modelingapp-engine-ndbwebapp2

Hardcoding values into ndb model


I am working in webapp2 framework using python, I have a parent class(Examplestart) which has three properties:

variable = ndb.KeyProperty(kind=DBUser)
time = ndb.DateTimeProperty(auto_now_add=True)
statement = ndb.StringProperty(indexed=False)

The Example has two children class(Example1 & Example2) , I want to hardcode properties in Examplestart such that:

my_example = DBExamplestart(
   variable = '776',
   statement = ['First']
)
my_example.put()

Where should I insert this code in my file ? If I use it inside Examplestart the code isn't working. my_example is related to class Example1.


Solution

  • You can set a default value in you child entity:

    class DBExamplestart(Examplestart):
        variable = ndb.KeyProperty(kind=DBUser, default=ndb.Key(DBUser, 776))
        statement = ndb.StringProperty(indexed=False, default='First')
    

    If you have more complex things to do (such as retrieving a particular id, instead of 776), you can look into Model Hooks. For example, _pre_put_hook() will allow you to do anything on your entity before you persist it.