使用模型继承时 ndb.KeyProperty 可以引用基模型类吗? [英] Can ndb.KeyProperty reference a base model class when using model inheritance?
问题描述
我有一些共享一组通用属性的模型,我在其他模型继承的基础模型类中定义了这些属性:
I have some models that share a common set of properties, which I have defined in a base model class from which other models inherit:
class BaseUser(ndb.Model):
name = ndb.StringProperty()
class DerivedUserA(BaseUser):
# some additional properties...
class DerivedUserB(BaseUser):
# some additional properties...
在其他一些模型中,我需要对任何 BaseUser
派生模型的引用:
In some other model, I need a reference to any BaseUser
-derived model:
class MainModel(ndb.Model):
user = ndb.KeyProperty(kind = BaseUser)
但是,当我尝试将 DerivedUserA
实体键设置为 MainModel.user
属性时,GAE 会引发 BadValueError
说明它是期待一个类型为 BaseUser
的密钥,但得到了一个 DerivedUserA
.
However, When I try to set a DerivedUserA
entity key to the MainModel.user
property, GAE raises a BadValueError
stating that it is expecting a key with kind BaseUser
but was given a DerivedUserA
.
如果我从我的 MainModel
中删除 kind
参数,它会起作用:
If I remove the kind
argument from my MainModel
, it works:
class MainModel(ndb.Model):
user = ndb.KeyProperty()
我可以接受,但我宁愿进行检查以确保我没有尝试在 MainModel.user
属性中保存任何类型的实体.有没有办法做到这一点?
I could live with that, but I'd rather have a check in place to make sure that I am not trying to save any kind of entity in the MainModel.user
property. Is there a way to do that?
推荐答案
使用 PolyModel 进行数据存储继承 -> https://developers.google.com/appengine/docs/python/ndb/polymodelclass
Use PolyModel for datastore inheritance -> https://developers.google.com/appengine/docs/python/ndb/polymodelclass
这篇关于使用模型继承时 ndb.KeyProperty 可以引用基模型类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!