【问题标题】:Can you access the previous value of a ndb property in _pre_put_hook?您可以访问 _pre_put_hook 中 ndb 属性的先前值吗?
【发布时间】:2018-01-31 10:57:51
【问题描述】:

我有一个ndb模型如下:

class SomeModel(ndb.Model):     
    name = ndb.StringProperty(default="")
    valid = ndb.BooleanProperty(default=False)

def some_function():
    print "fired"

当 name 属性从以前的值更改时,我希望触发 some_function() 函数。

例如

$ q = SomeModel.query().get()
$ print p.name 
John
$ q.name = "Sam"
$ q.put()
"fired"

但是,如果有效属性从False 更改为True,我不希望some_function() 触发。

例如

$ q = SomeModel.query().get()
$ print p.name
Sam
$ print p.valid 
False
$ q.valid = True
$ q.put()

使用_post_put_hook_pre_put_hook 是否可以访问属性的先前值,以便我可以选择触发或不触发外部函数?

【问题讨论】:

  • 我认为不运行另一个查询是不可能的。而且,由于您已经在模型之外完成了查询,因此使用它会更便宜:if q.name != new_name: ...

标签: python-2.7 google-app-engine app-engine-ndb


【解决方案1】:

这种方法对我来说总是有点 hacky,但它似乎有效。

您可以将实例上的属性值存储在_post_get_hook 中,并在_pre_put_hook(或_post_put_hook)中检索它们:

class Foo(ndb.Model):

    ...

    @classmethod
    def _post_get_hook(cls, key, future):
        instance = future.get_result()
        if instance:
            # Store 'old' instance data as an instance attribute
            instance._before = instance.to_dict()

    def _pre_put_hook(self):
        # Check if our storage attribute exists,
        # this could be a new instance.
        if hasattr(self, '_before'):
            # Do something with 'before' data
            ...
            # clean up
            del self._before 

编辑:

清理 - 如果您要在对象上多次调用 put,删除存储属性可能需要考虑一下。对于标准模型,您可以保留该属性,但这可能是 Expando 模型的问题,因为该属性将被写入数据存储区。

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 2020-02-05
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多