Can ndb.KeyProperty reference a base model class when using model inheritance?

蹲街弑〆低调 提交于 2019-12-13 13:14:50

问题


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...

In some other model, I need a reference to any BaseUser-derived model:

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

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.

If I remove the kind argument from my MainModel, it works:

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

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?


回答1:


Use PolyModel for datastore inheritance -> https://developers.google.com/appengine/docs/python/ndb/polymodelclass




回答2:


The reason this doesn't work is that the kind parameter to KeyProperty() gets translated to a string immediately.
Since it's only a validation feature, we could consider fixing this though.
If you like this idea, you could file a feature request in the tracker: http://code.google.com/p/appengine-ndb-experiment/issues/list -- this would be less heavyweight than PolyModel (although it seems PolyModel might be what you're looking for anyway).



来源:https://stackoverflow.com/questions/11971415/can-ndb-keyproperty-reference-a-base-model-class-when-using-model-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!