views:

67

answers:

1

I have a datastore model representing items in an ecommerce site:

class Item(db.Model):
    CSIN = db.IntegerProperty()
    name = db.StringProperty()
    price = db.IntegerProperty()
    quantity = db.IntegerProperty()

Is there some way to enforce integrity constraints? For instance, I would like to make sure that quantity is never set to be less than 0.

A: 

The Property constructor lets you specify a function with the 'validator' named argument. This function should take one argument, the value, and raise an exception if the valid is invalid. For example:

def range_validator(minval, maxval):
  def validator(v):
    if (minval is not None and v < minval) or (maxval is not None and v > maxval):
      raise ValueError("Value %s outside range (%s, %s)" % (v, minval, maxval))
  return validator

class Item(db.Model):
    CSIN = db.IntegerProperty()
    name = db.StringProperty()
    price = db.IntegerProperty()
    quantity = db.IntegerProperty(validator=range_validator(0, None))

Note that the example uses a nested function to define general-purpose validators - you can, of course, use simple functions if you want to write a more special purpose validator.

Nick Johnson