具有动态种类的 GAE NDB Expando 模型

GAE NDB Expando Model with dynamic Kind

是否可以将动态实体种类分配给 Expando 模型?例如,我想将此模型用于多种类型的动态实体:

class Dynamic(ndb.Expando):
    """
    Handles all "Post types", such as Pages, Posts, Users, Products, etc...
    """
    col = ndb.StringProperty()
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

现在我使用 "col" StringProperty 保存种类(如 "Pages"、"Posts" 等)并每隔一段时间查询 "col"时间.

阅读文档后,我偶然发现了这个@classmethod:

class MyModel(ndb.Model):
    @classmethod
    def _get_kind(cls):
         return 'AnotherKind'

这是否意味着我可以做到这一点?

class Dynamic(ndb.Expando):
    """
    Handles all "Post types", such as Pages, Posts, Users, Products, etc...
    """
    col = ndb.StringProperty()
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

    @classmethod
    def _get_kind(cls):
        return 'AnotherKind'

但是如何动态替换 'AnotherKind'?我可以做类似 return col 的事情吗?

谢谢!

我不知道您是否可以这样做,但这听起来很危险,而且 GAE 更新可能会破坏您的代码。

使用子类似乎是一种更安全的选择。像这样:

class Dynamic(ndb.Expando):
    parent = ndb.IntegerProperty()
    name = ndb.StringProperty()
    slug = ndb.StringProperty()

class Pages(Dynamic):
    pass

class Posts(Dynamic):
    pass

class Users(Dynamic):
    pass

您也可以尝试使用 PolyModel

我们需要更多地了解您的申请以及您想要完成的目标,以便提供更具体的建议。