Daniel D
Daniel D

Reputation: 3677

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!

Upvotes: 1

Views: 2306

Answers (2)

Mark Lavin
Mark Lavin

Reputation: 25164

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.

Upvotes: 5

Kyle Wild
Kyle Wild

Reputation: 8915

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).

Upvotes: 0

Related Questions