必需的自定义属性

时间:2011-08-04 10:34:29

标签: google-app-engine properties google-cloud-datastore required

我创建了一个自定义db.Property子类:

class PropertyFoo(db.StringProperty):
  def validate(self, value):
    # Yes this is a pointless validator, but please read on
    return value

  def get_value_for_datastore(self, model_instance):
    return super(PropertyFoo, self).get_value_for_datastore(model_instance)

  def make_value_from_datastore(self, value):
    return super(PropertyFoo, self).make_value_from_datastore(value)

现在我还创建了一个db.Model子类:

class ModelFoo(db.Model):
  foo = PropertyFoo(required=True)

所以我测试了它们:

>>> m = ModelFoo()
# No errors :(
>>> m.foo
# No errors still
>>> print m.foo
'None' # <-- Why???

我应该期待一个错误:

BadValueError: Property foo is required

如何确保我的自定义Property子类required引发BadValueError?我错过了PropertyFoo定义中的内容吗?

1 个答案:

答案 0 :(得分:3)

我相信你需要调用超类的validate方法:

class PropertyFoo(db.StringProperty):
  def validate(self, value):
    super(PropertyFoo, self).validate(value) #Base implementation checks
    #Do your other check here raising BadValueError
    return value