为 Google 数据存储计算 属性

Computed Property for Google Datastore

我不确定具体是如何实现的。

我有一个定义为

的模型
class Post(ndb.Model):
    author_key = ndb.KeyProperty(kind=Author)
    content = ndb.StringProperty(indexed=False)
    created = ndb.DateTimeProperty(auto_now_add=True)
    title = ndb.StringProperty(indexed=True)
    topics = ndb.StructuredProperty(Concept, repeated=True)
    concise_topics = ndb.ComputedProperty(get_important_topics())

    @classmethod
    def get_important_topics(cls):
        cls.concise_topics = filter(lambda x: x.occurrence > 2, cls.topics)
        return cls.concise_topics

我喜欢将 concise_topics 的值(与主题属于同一类型)设置为通过 get_important_topics 方法获得的子集。这应该在设置主题 属性 时发生。

如何在 Post class 中定义 "concise_topics" 属性?

使用 class 方法,您无权访问实例值。而且你不应该调用函数,只传递给计算属性,让它自己调用。

class Post(ndb.Model):
    author_key = ndb.KeyProperty(kind=Author)
    content = ndb.StringProperty(indexed=False)
    created = ndb.DateTimeProperty(auto_now_add=True)
    title = ndb.StringProperty(indexed=True)
    topics = ndb.StructuredProperty(Concept, repeated=True)

    def get_important_topics(self):
        return filter(lambda x: x.occurrence > 2, self.topics)

    concise_topics = ndb.ComputedProperty(get_important_topics)

据我所知,计算的 属性 是在每次 put 调用时设置的,因此到那时您的主题应该已经存在。