Niks Jain
Niks Jain

Reputation: 1647

Google App Engine: How to Set Default Value from a property to another property in db.Model Class?

My App having db class,

class invoice(db.Model):
   location_code = db.StringProperty()
   invoice_no = db.IntegerProperty()
   product_tax_rate = db.FloatProperty()
   basic_tax_rate = db.FloatProperty()
   addl_tax_rate = db.FloatProperty()
   .
   .
   .

In this, i wanted to set product_tax_rate's value as default value for property basic_tax_rate's property if addl_tax_rate's value is 0.

How can i add a generic procedure for this logic in this class method?

Please let me know if you still not getting this requirement.

Upvotes: 0

Views: 777

Answers (3)

Guido van Rossum
Guido van Rossum

Reputation: 16890

Just do it manually in the code where you create new instances of your entity. Or override the constructor (but that sounds like it would just be leading you on to more debugging mysteries).

Upvotes: 0

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

You can use NDB and ComputedProperty todo something like:

class invoice(ndb.Model):
   product_tax_rate = ndb.ComputedProperty(lambda self: self.basic_tax_rate if self.addl_tax_rate == 0 else ???)
   basic_tax_rate = ndb.FloatProperty()
   addl_tax_rate = ndb.FloatProperty()

Upvotes: 2

Paul Collingwood
Paul Collingwood

Reputation: 9116

You could use a model hook: https://developers.google.com/appengine/docs/python/ndb/entities#hooks

By defining a hook, an application can run some code before or after some type of operations; for example, a Model might run some function before every get().

So when addl_tax_rate is 0 you just need some logic that would set the values accordingly when the model is put into the datastore. Something like:

def _pre_put_hook(self):
if self.addl_tax_rate == 0:
    self.basic_tax_rate = self.product_tax_rate

That code is not tested.

Upvotes: 1

Related Questions