【问题标题】:How to get the dirty factors of an NDB Model in pre_put_hook如何在 pre_put_hook 中获取 NDB 模型的脏因子
【发布时间】:2013-05-02 01:37:12
【问题描述】:

是否可以在pre_put_hook 中计算出实体的脏因子?

我想根据put 有条件地执行一些回调。例如。如果实体的特定属性已更改,我想发送邮件通知。我可以在调用put() 之前手动执行此操作,但如果方法失败,则put() 也不会被调用。

【问题讨论】:

    标签: app-engine-ndb djangoappengine


    【解决方案1】:

    Brian M. Hunt suggestion 之后,我使用以下代码检查脏因素。在本例中,我检查了一个名为 status 的属性:

    class Blog(ndb.Model):
      status = ndb.IntegerProperty(default=0)
    
      def __init__(self, *args, **kwargs):
        # make sure the __old_status__ exists when you `new' an object
        # instead of getting it from DataStore. e.g. b = Blog(status=1)
        super(Blog, self).__init__(*args, **kwargs)
        self.__old_status__ = self.status # I check the status only
    
      @classmethod
      def _post_get_hook(cls, key, future):
        obj = future.get_result()
        setattr(obj, '__old_status__', obj.status)
    
      def _pre_put_hook(self):
        if (not self.key.id() or self.__old_status__ != self.status)  and (self.status == 1):
          # the blog is (either a new blog or an existing blog) AND its status is changed to published (e.g. value = 1)
          # do sth e.g. save the time when it is published, update FB object cache and etc.
          pass
    

    【讨论】:

    • 感谢您的回答。我已经很多年没有接触过这个项目,不幸的是,我无法验证这个答案是否正确(无需重新学习 NDB 的所有工作方式),所以我无法将其标记为已接受。不过,在一些优秀的网友出现并验证这是一个很好的答案之前,请投票表示感谢!
    • 我已验证此解决方案有效并且是可接受的答案。
    【解决方案2】:

    您可以通过在 ndb.Model 上定义 _post_get_hook_pre_put_hook 来分别保存属性的原始值并将放入的值与原始值进行比较。

    【讨论】:

      【解决方案3】:

      抱歉,这不是 NDB 功能。

      【讨论】:

      • 你能建议另一种方法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多