[Fixed]-Django – Polymorphic Models or one big Model?

11👍

My recommendation, in general with database design, is to avoid inheritance. It complicates both the access and updates.

In Django, try using an abstract class for your base model. That means a db table will not be created for it. Its fields/columns will be auto-created in its child models. The benefit is: code reuse in Django/Python code and a simple, flat design in the database. The penalty is: it’s more work to manage/query a mixed collection of child models.

See an example here: Django Patterns: Model Inheritance

Alternatively, you could change the concept of “Mammal” to “MammalTraits.” And include a MammalTraits object inside each specific mammal class. In code, that is composition (has-a). In the db, that will be expressed as a foreign key.

2👍

We ended up going with a large table with a lot of usually-empty columns. Our reasoning was that (in this case) our Mammal table was all we’d be querying over, and there was no (intuitive) way to filter out by certain types of Mammals besides manually checking whether they had a “dolphin” or “elephant” object, which then threw an error if they didn’t. Even looking for the type of an object returned from a query that was definitely an Elephant still returned “Mammal”. It would be hard to extend any Pythonic workarounds to writing pure SQL, which one of our data guys does regularly.

Leave a comment