简体   繁体   中英

Django Model Inheritance and Relationships

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!

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.

It is supported, and won't cause scalability problems. My advice, however, is that you only refer to the Child classes (ie 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM