【问题标题】:Can ndb.KeyProperty reference a base model class when using model inheritance?使用模型继承时,ndb.KeyProperty 可以引用基模型类吗?
【发布时间】:2023-03-18 17:00:01
【问题描述】:

我有一些模型共享一组公共属性,我在其他模型继承的基础模型类中定义了这些属性:

class BaseUser(ndb.Model):
    name = ndb.StringProperty()

class DerivedUserA(BaseUser):
    # some additional properties...

class DerivedUserB(BaseUser):
    # some additional properties...

在其他一些模型中,我需要引用任何BaseUser-derived 模型:

class MainModel(ndb.Model):
    user = ndb.KeyProperty(kind = BaseUser)

但是,当我尝试将 DerivedUserA 实体键设置为 MainModel.user 属性时,GAE 会引发 BadValueError 声明它期望使用类型为 BaseUser 的键,但得到的是 DerivedUserA

如果我从 MainModel 中删除 kind 参数,它会起作用:

class MainModel(ndb.Model):
    user = ndb.KeyProperty()

我可以接受,但我宁愿进行检查以确保我没有尝试在 MainModel.user 属性中保存任何类型的实体。有没有办法做到这一点?

【问题讨论】:

    标签: google-app-engine app-engine-ndb


    【解决方案1】:

    使用 PolyModel 进行数据存储继承 -> https://developers.google.com/appengine/docs/python/ndb/polymodelclass

    【讨论】:

    • 哇,即使在过去 2 天沉浸在 ndb 的文档中之后,这门课还是不为人知。非常感谢!
    【解决方案2】:

    这不起作用的原因是KeyProperty() 的 kind 参数会立即转换为字符串。
    由于它只是一个验证功能,我们可以考虑解决这个问题。
    如果您喜欢这个想法,您可以在跟踪器中提交功能请求:http://code.google.com/p/appengine-ndb-experiment/issues/list - 这将比 PolyModel 更轻量级(尽管 PolyModel 似乎是您正在寻找的东西)。

    【讨论】:

    • 谢谢!事实上,PolyModel 是我所需要的,因为它解决了我在初始模型继承时遇到的另一个问题,即我无法在所有 BaseUser 派生实体之间执行查询(因为它们存储在不同的数据存储表中)。我不认为我会要求您在 KeyProperty 中解决此问题,因为 PolyModel 似乎确实是正确进行模型继承的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多