Django Model Inheritance and Relationships

混江龙づ霸主 提交于 2019-12-13 18:21:13

问题


I've got a django app, where I'd like to define a relationship between two classes at a base level. It also makes sense to me to define the relationship between the children of those base classes - so that I get something like this:

class BaseSummary(models.Model):
  base_types...

class BaseDetail(models.Model):
  base_detail_types...
  base_summary = models.ForeignKey('BaseSummary')

class ChildSummary(BaseSummary):
  child_summary_types...  

class ChildDetail(BaseDetail):
  child_detail_type...
  child_summary = models.ForeignKey('ChildSummary')

Does django support this? and If it is supported, is something like this going to cause scalability problems?

Thanks!


回答1:


Yes, this is supported. Yes, it can cause performance problems. You should read Jacob's post on model inheritance: http://jacobian.org/writing/concrete-inheritance/

Since 1.0, Django’s supported model inheritance. It’s a neat feature, and can go a long way towards increasing flexibility in your modeling options.

However, model inheritance also offers a really excellent opportunity to shoot yourself in the foot: concrete (multi-table) inheritance. If you’re using concrete inheritance, Django creates implicit joins back to the parent table on nearly every query. This can completely devastate your database’s performance.




回答2:


It is supported, and won't cause scalability problems. My advice, however, is that you only refer to the Child classes (i.e. don't create references to the Base classes, and don't instantiate them).

Base Model Classes should be extend-only (sort of like an Abstract Class in other languages).



来源:https://stackoverflow.com/questions/4695458/django-model-inheritance-and-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!