Django - Polymorphic Models or one big Model?

后端 未结 2 2068
执笔经年
执笔经年 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.

提交回复
热议问题