Djang中的单表继承

2024-05-16 10:07:11 发布

您现在位置:Python中文网/ 问答频道 /正文

Django中是否明确支持单表继承?上次我听说,这个功能还在开发和讨论中。

同时,我是否可以使用库/黑客来捕获基本行为?我有一个混合不同对象的层次结构。有一个雇员类、雇员类型的子类和一个经理id(父id)的公司结构的典型示例将是我正在解决的问题的一个很好的近似。

在我的例子中,我想表达这样一个想法:一个员工可以管理其他员工,同时由另一个员工管理。经理和工人没有单独的类,这使得这很难在表中分布。子类将代表程序员、会计师、销售人员等类型的员工,并且独立于谁监管谁(好吧,我想在某些方面它不再是一个典型的公司)。


Tags: 对象django功能id示例类型层次结构员工
3条回答

目前在Django-MTI(模型表继承)和ABC(抽象基类)中有两种继承形式。

我写了一篇tutorial关于引擎盖下面发生的事。

您还可以参考model inheritance上的官方文档。

我认为OP询问单表继承是defined here

Relational databases don't support inheritance, so when mapping from objects to databases we have to consider how to represent our nice inheritance structures in relational tables. When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.

也就是说,一个数据库表用于实体类的整个层次结构。Django不支持这种继承。

看看我的尝试:

http://djangosnippets.org/snippets/2408/

An emulation of "table per hierarchy" a.k.a. "single table inheritance" in Django. The base class must hold all the fields. It's subclasses are not allowed to contain any additional fields and optimally they should be proxies.

不完全是“单表继承”,但在很多情况下已经足够接近了。

相关问题 更多 >