如何使用Google Appengine ndb跨属性进行验证?

问题描述 投票:3回答:1

说我有一个具有两个属性的类,如下所示:

class Banana(ndb.Model):
    is_delicious = ndb.BooleanProperty(default=True)
    is_rotten = ndb.BooleanProperty(default=False)

Banana条目不能很好吃。如何防止将腐烂的香蕉保存到数据存储中?

我可以像__init__一样重写this answer方法,但这不能防止某人更新香蕉到不可能的状态。

文档显示validator option,但这不适用于所有字段。

如何相互验证模型的两个字段,以防止将对象保存为错误状态?

google-app-engine app-engine-ndb
1个回答
3
投票

这不会阻止某人将香蕉更新为不可能的状态。

数据存储区独自提供几乎零模式实施。

您可以打开数据存储区(https://console.cloud.google.com/datastore/entities)的Web控制台,选择一个实体并开始从中删除属性,即使ndb代码在定义属性时具有required=True,也是如此

enter image description here

在图片中,我可以将字段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代码正在访问数据库时才有效

© www.soinside.com 2019 - 2024. All rights reserved.