0

是否可以将动态实体类型分配给Expando模型?例如,我想用这种模式对于许多类型的动态实体:带动态类型的GAE NDB 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() 

现在我用的是“山坳” StringProperty持有类(如“页面”,“文章”,等等)和查询每次都是“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吗?

谢谢!

+0

我认为(阅读行之间),你应该仔细看看PolyModel。 –

回答

1

我不知道你是否可以这样做,但这听起来很危险,并且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

我们需要了解更多关于您的应用程序以及您想要完成的更多具体建议。