Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricky model inheritance - Django

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!

like image 676
RadiantHex Avatar asked Mar 22 '10 02:03

RadiantHex


People also ask

What are the model inheritance style in Django?

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.

How can create primary key in Django model?

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.

What is abstract inheritance in Django?

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.

What is proxy model in Django?

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.


1 Answers

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):
    # ...
like image 84
Alex Martelli Avatar answered Sep 21 '22 03:09

Alex Martelli