您可以访问 _pre_put_hook 中 ndb 属性 的先前值吗?
Can you access the previous value of a ndb property in _pre_put_hook?
我有一个如下的ndb模型:
class SomeModel(ndb.Model):
name = ndb.StringProperty(default="")
valid = ndb.BooleanProperty(default=False)
def some_function():
print "fired"
当名称 属性 与之前的名称发生变化时,我希望触发 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
有没有办法访问 属性 的先前值,以便我可以选择触发或不触发外部函数?
这种方法对我来说总是有点老套,但它似乎有效。
您可以在 _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 模型的问题,因为该属性将被写入数据存储。
我有一个如下的ndb模型:
class SomeModel(ndb.Model):
name = ndb.StringProperty(default="")
valid = ndb.BooleanProperty(default=False)
def some_function():
print "fired"
当名称 属性 与之前的名称发生变化时,我希望触发 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
有没有办法访问 属性 的先前值,以便我可以选择触发或不触发外部函数?
这种方法对我来说总是有点老套,但它似乎有效。
您可以在 _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 模型的问题,因为该属性将被写入数据存储。