Django,多表继承不好吗? [英] Django, multi-table inheritance is that bad?

查看:114
本文介绍了Django,多表继承不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这并不是真正针对django的.

This isn't really specific to django.

一个可以建模

Place (with location, name, and other common attributes)
 - Restaurant  (menu..)
 - ConcertHall  (hall size..)

  1. 放在两个单独的表中,并让每个表保存它们所需的所有字段. (在django世界中,这称为抽象继承)
  2. 在三个表中,其中一个表包含公共字段,另外两个表具有自己的唯一字段. (Django中的多表继承)

这本书的作者

The authors of book Two scoops of Django 1.8 strongly advise against using multi-table inheritance.

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

Say you want to query places based on it's location and paginate the results (It doesn't have to be a location, can be any other common attribute we want to filter on)

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

I can see how I can achieve it using Multi-table inheritance.

从位置餐厅"左侧的"JOIN OUTER JOIN"中选择place.id restuarant.id = place.id)在( Concerthall.id = place.id),其中...按距离排序

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

用抽象继承做到这一点是否可行?

Is it feasible to do it with abstract inheritance?

推荐答案

根据 Django文档:模型继承:

您唯一需要做出的决定是,您是否希望父模型成为自己的模型(具有自己的数据库表),还是希望父模型只是那些只能通过子项可见的公共信息的持有者?模型.

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.

我认为这两种可能性都只是工具,同样是好工具,这取决于您的用例是否适当.当然,这两种方法都需要考虑一些具体的事情,并且从概念上讲,有时有时很难理解多表继承,但除此之外,这个话题只会变得自以为是.

I think both possibilities are just tools, equally good tools and it just depends on your use case for their appropriateness. Surely there are specific things to consider for both approaches, and conceptually sometimes multi-table inheritance may be more difficult to comprehend, but other than that this topic just turns to become opinionated.

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

If you need a single queryset for both models, then it is logical that you consider multi-table inheritance rather than abstract models, because otherwise you would need to get into combining two querysets into one, most probably by using lists as this relevant answer suggests, but you would definitely lose ORM functionality.

这篇关于Django,多表继承不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆