说我有一个具有两个属性的类,如下所示:
class Banana(ndb.Model):
is_delicious = ndb.BooleanProperty(default=True)
is_rotten = ndb.BooleanProperty(default=False)
烂Banana
条目不能很好吃。如何防止将腐烂的香蕉保存到数据存储中?
我可以像__init__
一样重写this answer方法,但这不能防止某人更新香蕉到不可能的状态。
文档显示validator option,但这不适用于所有字段。
如何相互验证模型的两个字段,以防止将对象保存为错误状态?
这不会阻止某人将香蕉更新为不可能的状态。
数据存储区独自提供几乎零模式实施。
您可以打开数据存储区(https://console.cloud.google.com/datastore/entities)的Web控制台,选择一个实体并开始从中删除属性,即使ndb
代码在定义属性时具有required=True
,也是如此
在图片中,我可以将字段completed
编辑为布尔值而不是日期时间,然后每当通过ndb
提取此实体时,appengine都会引发异常。
所以我不知道那会离开你。您可以走__init__
路线
您可以将支票放入_pre_put_hook
:
class Banana(ndb.Model): is_delicious = ndb.BooleanProperty(default=True) is_rotten = ndb.BooleanProperty(default=False) def _pre_put_hook(self): if self.is_delicious and self.is_rotten: raise Exception("A rotten Banana entry cannot be delicious")
您可以让
ComputedProperty
进行检查:
class Banana(ndb.Model): is_delicious = ndb.BooleanProperty(default=True) is_rotten = ndb.BooleanProperty(default=False) def _is_valid(self): if self.is_delicious and self.is_rotten: raise Exception("A rotten Banana entry cannot be delicious") return True is_valid = ndb.ComputedProperty(lambda self: self._is_valid())
但是所有这些仅在您的
ndb
代码正在访问数据库时才有效