pypypy
pypypy

Reputation: 1105

Is it better to combine model subclasses and have un-used fields, or create concrete subclasses?

I'm writing an app in Django and I have an instance where I would like to create a model with a single layer of inheritance to a number of sub classes. i.e:

Vehicles -> Cars, Bikes, Busses

I need to be able to search and store items as the Vehicle superclass, but the downcast to the subclass to use additional fields in most cases. In Django, this will cause a lot of hits to the database to retrieve sub-models, or a massive join and query.

Should I use the concrete subclasses and take the performance hit, or should I add the extra fields to one vehicle model and then have unused fields in various objects?

I should note that the additional fields are typically 1-3 fields of small size i.e. Char strings, and that a total of 4 subclasses (max 9 unused fields per model)

Upvotes: 1

Views: 141

Answers (1)

idik
idik

Reputation: 882

The basic answer to this question is - wherever you can evoid a 'JOIN' in a SQL database scheme, you should avoid it.

The reason for this, is that the complexity for a JOIN command is the highest and takes the most time. So in general, The recommendation is as following:

  1. If the relationship is a OneToOne, and you know this relationship would never become a OTM (OneToMany), then put all in the same table.
  2. If the relationship is OTO but contains a high-risk content (like password hashes, etc.) you should avoid putting it on the same table, for security reasons.
  3. If the relationship is OTM or MTM , you don't really have a choice other than splitting it up.

Upvotes: 1

Related Questions