1

在我的 GAE 项目中,我有一个名为 Part 的基类。从这个类我派生出其他类,如电机和电池。

如果我运行以下命令:

motors   = Motor.query().fetch()
batterys = Battery.query().fetch()

我会得到所有的零件,但我正在寻找更优雅的东西。如果我运行:

parts    = Part.query().fetch()

我得到一个空列表 [ ]。

如何运行上述查询并在一个列表中获取所有结果?谢谢

4

2 回答 2

2

You can do this, but all your Parts classes must inherit from PolyModel

https://developers.google.com/appengine/docs/python/ndb/polymodelclass

So

class Part(ndb.PolyModel):
  #stuff

class Motor(Part):
  # stuff

class Wheel(Part):
  # stuff

parts = Part.query().fetch()

However all items are stored in the datastore as Part, they have an additional classes attribute which names each of the classes in it's inheritance heirarchy. Then when the entity is retrieved the correct sub class is instantiated.

Another potential downside, the property names in the stored model are a union of all subclasses, if you have default values for any of the properties. I haven't checked to see how far this goes. So if you have lots of very different properties in all the subclasses you could be storing a lot of empty properties, and incur the cost of storing all the property names in each entity.

于 2013-11-10T22:58:27.797 回答
1

数据存储没有继承的概念,也不知道您的实体类型派生自 Part。

使用 GAE 并没有真正的方法来做这种事情:祖先键并不是真正的答案,因为它们会使所有电机/电池实体都从单个部件下降,这将严重限制更新速率。

对这种关系建模的最佳方法实际上是删除单独的模型并拥有一个单独的 Part 模型,其part_type字段可以是"motor"or "battery"

于 2013-11-10T18:44:11.917 回答