Can ndb.KeyProperty reference a base model class w

2019-06-27 16:38发布

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?

2条回答
唯我独甜
2楼-- · 2019-06-27 17:20
小情绪 Triste *
3楼-- · 2019-06-27 17:40

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

查看更多
登录 后发表回答