将模型更改为从抽象基类继承而不更改DB

时间:2022-09-24 23:41:23

I have a simple model for a product that looks like this:

我有一个简单的产品模型,如下所示:

class Product(models.Model):
    name = models.CharField(max_length=80)
    # other attributes

We already have this rolled out, and have a DB with these fields filled out. I want to change this model to inherit from a base class, that looks like this:

我们已经推出了这个,并填写了这些字段的数据库。我想将此模型更改为从基类继承,如下所示:

class BaseProduct(models.Model):
    name = models.CharField(max_length=80)

    class Meta(object):
         abstract = True

And modify the Product class like so:

并修改Product类,如下所示:

class Product(BaseProduct):
    # other attributes

Based on my understanding of Abstract Base Classes, these two setups will create the same tables (right?). So technically, after changing this model, I shouldn't have to do any modifications in the database. However, when I try to apply it using South, it wants to drop the 'name' column of the Product table.

根据我对抽象基类的理解,这两个设置将创建相同的表(对吗?)。从技术上讲,在更改此模型后,我不必在数据库中进行任何修改。但是,当我尝试使用South应用它时,它想要删除Product表的'name'列。

Since we already have these tables rolled out, I would ideally like to keep the 'name' column, as opposed to using other solutions (like a OneToOneField).

由于我们已经推出了这些表,因此我希望保留“名称”列,而不是使用其他解决方案(如OneToOneField)。

Thanks!

谢谢!

1 个解决方案

#1


0  

You cannot override model fields of the same name in Django, which is why South is asking you to remove the 'name' field from the child class. See https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted for further details.

你不能覆盖Django中同名的模型字段,这就是为什么South要求你从子类中删除'name'字段。有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted。

You may need to export the existing name from each row and map them back into the updated table (perhaps by using row id as the key).

您可能需要从每行导出现有名称并将它们映射回更新的表(可能使用行ID作为键)。

#1


0  

You cannot override model fields of the same name in Django, which is why South is asking you to remove the 'name' field from the child class. See https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted for further details.

你不能覆盖Django中同名的模型字段,这就是为什么South要求你从子类中删除'name'字段。有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted。

You may need to export the existing name from each row and map them back into the updated table (perhaps by using row id as the key).

您可能需要从每行导出现有名称并将它们映射回更新的表(可能使用行ID作为键)。