【问题标题】:set Property value automatically in app engine Model Class在应用引擎模型类中自动设置属性值
【发布时间】:2013-12-15 16:05:44
【问题描述】:

如何从模型(datastore ndb.Model)内部设置模型属性的值?

class Note(ndb.Model):
    content = ndb.StringProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)
    depth = ndb.IntegerProperty()

    def _calculate_depth(self):
        self.depth = len(self.key.parent().pairs())

note = Note( parent=ndb.Key('Note', 'main', 'Todo', 'task1') , content='whatever')
note.put()

我正在寻找的是,当运行 create new note calculate_depth 方法时,它会设置 depth 属性的值

解决方案:)

class Note(ndb.Model):
    content = ndb.StringProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)
    depth = ndb.ComputedProperty(lambda self: len(self.key.parent().pairs()))


note = Note( parent=ndb.Key('Note', 'main', 'Todo', 'task1') , content='whatever')
note.put()

【问题讨论】:

  • 我正在寻找的是 ComputedProperty,感谢@Jimmy Kane 我得到了它

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


【解决方案1】:

抱歉之前的事情。

你要找的是帖子PUT hooks.

我看到在您的函数_calculate_depth 中您使用实体键的值。那么实体不仅需要创建,还需要写入ndb来key一个key。

如果您希望“自动”发生这种情况,那么 Model__post_put_hook 就是您所需要的

【讨论】:

  • @KAl-Mazrouai 比请检查此答案的正确性并欢迎使用 stackoverflow。
  • 我认为以前的答案也很有效,其他人同时保留这两种解决方案会有所帮助
  • @KAl-Mazrouai 很高兴听到。应用引擎有一些更漂亮的功能。还要寻找结构化属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
相关资源
最近更新 更多