Move a python / django object from a parent model to a child (subclass)

后端 未结 5 1187
[愿得一人]
[愿得一人] 2021-01-03 01:44

I am subclassing an existing model. I want many of the members of the parent class to now, instead, be members of the child class.

For example, I have a model Swall

5条回答
  •  臣服心动
    2021-01-03 01:56

    Depends on what kind of model inheritance you'll use. See http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance for the three classic kinds. Since it sounds like you want Swallow objects that rules out Abstract Base Class.

    If you want to store different information in the db for Swallow vs AfricanSwallow vs EuropeanSwallow, then you'll want to use MTI. The biggest problem with MTI as the official django model recommends is that polymorphism doesn't work properly. That is, if you fetch a Swallow object from the DB which is actually an AfricanSwallow object, you won't get an instance o AfricanSwallow. (See this question.) Something like django-model-utils InheritanceManager can help overcome that.

    If you have actual data you need to preserve through this change, use South migrations. Make two migrations -- first one that changes the schema and another that copies the appropriate objects' data into subclasses.

提交回复
热议问题