具有相互依赖属性的Ndb模型验证?

时间:2015-11-06 09:32:26

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

我想验证NDB模型。我的模型类似于:

class Sample(ndb.Model):
  x = ndb.IntegerField()
  y = ndb.IntegerField()

我想确保x<在任何时间点。

我尝试过的方法:

  1. 写入Validator函数并从重写的构造函数中调用它。但是字段值可能会在以后更改。它应该在每次保存时验证

  2. 添加一个_pre_put_hook - 但这似乎有点矫枉过正。另外 - 在实体实际保存在数据存储区

  3. 之前,不会抛出错误

    理想情况下,我想要的是每当a或b被更改时 - 应该触发一个函数,它将验证实体是否有效,否则抛出错误。

    注意:目前我正在使用_pre_put_hook。

1 个答案:

答案 0 :(得分:0)

这应该在ndb.Model逻辑之外完成。

只需在模型中创建一个函数,如下所示:

class Sample(ndb.Model):
   x = ndb.IntegerField()
   y = ndb.IntegerField()

   @classmethod
   def new(cls, x, y):
     if x >= y:
        raise Exception
     return cls(x=x, y=y)

然后将我使用的通用Exception替换为自定义Exception并使用try块捕获它。

相关问题