如何获取 App Engine 模型类的所有实体,包括其子类的实体?

发布于 2024-10-04 13:44:53 字数 366 浏览 2 评论 0原文

我有一个关于 Google App Engine 和查询数据存储区的问题。

假设我有三个类:

class Animal(db.Model):
   age = db.IntegerProperty()

class Giraffe(Animal):
   # ...

class Mouse(Animal):
   # ...

现在我想获取所有 Animal 实体。我可能会尝试

Animal.all()

但这不会返回任何内容(我使用长颈鹿和鼠标构造函数创建了所有动物实体)。

如何获得所有动物实体?一般方法(db.Modell子类的子类)可以吗?

I've got a question about Google App Engine and querying the datastore.

Suppose I've got three classes:

class Animal(db.Model):
   age = db.IntegerProperty()

class Giraffe(Animal):
   # ...

class Mouse(Animal):
   # ...

Now I want to get all the Animal entities. I might try

Animal.all()

But that doesn't return anything (I created all the Animal entities using the Giraffe and Mouse constructors).

How do I get all the Animal entities? Is the general approach (subclasses of a subclass of db.Modell) ok?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别再吹冷风 2024-10-11 13:44:53

App Engine 不直接支持类继承,但 SDK 中内置了一个扩展,名为 PolyModel 确实如此。修改您的 Animal 类以扩展 PolyModel 而不是 Model,一切都会按您期望的方式工作。

App Engine doesn't directly support class inheritance, but there's an extension built into the SDK called PolyModel that does. Modify your Animal class to extend PolyModel instead of Model, and everything will work the way you expect.

月野兔 2024-10-11 13:44:53

数据存储不会像这样跟踪继承。每个实体都有一个单一的“种类”。

如果您希望所有动物都是同一种类,您可以拥有一个属性来指示它是哪种动物(长颈鹿或老鼠)。因此,您可以将每个新实体设置为 Animal,然后将“type”属性或其他属性设置为 Giraffe 或 Mouse。通过这种方式,您会失去一些继承的好特性,这是一种拖累。

The datastore doesn't keep track of inheritances like this. Each Entity has a single "kind".

If you wanted all of the animals to be of the same kind, you could have a property that indicates which sort of animal (Giraffe or Mouse) it is. So, you'd make each new entity an Animal, but then set the "type" property or whatever to Giraffe or Mouse. You lose some of the nice features of inheritance this way, which is a drag.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文