I think this is a bit tricky, at least for me. :)
So I have 4 models Person, Singer, Bassist and Ninja.
Singer, Bassist and Ninja inherit from Person.
The problem is that each Person can be any of its subclasses.
e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a Ninja. Another one can be all three.
How should I organise my models?
Help would be much appreciated!
Models inheritance works the same way as normal Python class inheritance works, the only difference is, whether we want the parent models to have their own table in the database or not. When the parent model tables are not created as tables it just acts as a container for common fields and methods.
By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.
An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.
A proxy model is a subclass of a database-table defining model. Typically creating a subclass of a model results in a new database table with a reference back to the original model's table - multi-table inheritance. A proxy model doesn't get its own database table. Instead it operates on the original table.
Multiple inheritance doesn't work well with databases (and your Django models do need to map down to a database in the end), and inheritance is often a bad way to model "roles" (because people's roles do change). I would have Singer, Bassist and Ninja as "roles", not as subclasses of Person, and connect them via foreign keys:
class Singer(models.Model):
person = models.ForeignKey('Person')
# ...
class Person(models.Model):
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With