Django,多表继承有那么糟糕吗?

标签 django database-design model

这并不是 django 特有的。

一个可以模型

Place (with location, name, and other common attributes)
 - Restaurant  (menu..)
 - ConcertHall  (hall size..)
  1. 在两个单独的表中,让每个表保存它们需要的所有字段。 (在 django 世界中,这称为抽象继承)
  2. 在三个表中,其中一个包含公共(public)字段,另外两个有自己的唯一字段。 (django中的多表继承)

本书的作者Two scoops of Django 1.8强烈建议不要使用多表继承。

假设您想要根据位置查询地点并对结果进行分页(不一定是位置,可以是我们要过滤的任何其他常见属性)

我可以看到如何使用多表继承来实现它。

select place.id from place LEFT OUTER JOIN "restaurant" on ( restuarant.id=place.id) LEFT OUTER JOIN "concerthall" on ( concerthall.id=place.id) where ... order by distance

用抽象继承来实现可行吗?

最佳答案

根据Django documentation: Model inheritance :

The only decision you have to make is whether you want the parent models to be models in their own right (with their own database tables), or if the parents are just holders of common information that will only be visible through the child models.

我认为这两种可能性都只是工具,同样是好的工具,这仅取决于您的用例是否合适。当然,这两种方法都需要考虑特定的事情,并且从概念上讲,有时多表继承可能更难以理解,但除此之外,这个主题就会变得固执己见。

如果您的两个模型都需要一个查询集,那么您考虑多表继承而不是抽象模型是合乎逻辑的,因为否则您将需要将两个查询集合并为一个,最有可能通过使用列表来实现relevant answer建议,但你肯定会失去 ORM 功能。

关于Django,多表继承有那么糟糕吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476643/

相关文章:

model - Factory Boy 可以像 Model Mommy 那样自动生成 Django 模型字段值吗?

Ember.JS - 提交按钮运行查询并将 JSON 对象返回到模板。我是在服务中、作为模型还是在 route 运行查询?

python - 在 db 中保存二进制对象时,django-debug-toolbar 会崩溃。有解决方法吗?

mysql - 为父类(super class)型表强制执行单一子类型 SQL 表

mysql - 自动表规范化

mysql - 外键可能来自不同表的数据库设计

python - ValueError : The field admin. LogEntry.user 是用惰性引用声明的

django - 表单中的动态选择字段

python - 如何在 Django 中删除 ManyToMany 字段的实例

Java实体表模型