Django - Polymorphic Models or one big Model?

后端 未结 2 2041
执笔经年
执笔经年 2021-02-19 08:00

I\'m currently working on a model in Django involving one model that can have a variety of different traits depending on what kind of object it is. So, let\'s say we have a mod

相关标签:
2条回答
  • 2021-02-19 08:27

    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.

    0 讨论(0)
  • 2021-02-19 08:31

    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.

    0 讨论(0)
提交回复
热议问题