我需要从另一个模型扩展一个模型。
案例:
core/models.py
class Master(models.Model):
code = models.CharField(max_length=30, unique=True)
name = models.CharField(max_length=100, blank=False, null=False)
class Meta:
abstract = True
class City(Master):
zipcode = models.IntegerField()
custom/models.py
from core.models import City
class City(City)
newfield = models.CharField(max_length=20)
自定义是一个应用程序。
我尝试过代理模型,但它不是我需要的,因为代理模型添加了一个新表。 https://docs.djangoproject.com/en/2.2/topics/db/models/#proxy-models
我需要的是在迁移时将新字段添加到 City。
More info. In core the table is created and in custom you can add new fields that the client needs. The idea is that core is only maintained as standard.
最佳答案
代理模型不添加新表。来自docs link you mentioned :
The MyPerson class operates on the same database table as its parent Person class.
如果您想要一个名为 core_city
的表,另一个名为 custom_city
的表,第二个表有一个额外的字段,您只需将其子类化即可。也许使用别名会更容易:
from core.models import City as CoreCity
class City(CoreCity):
newfield = models.CharField(max_length=20)
custom_city
将包含 core_city
中的所有字段,外加一个 newfield
。在文档部分 Multi-table inheritance 中介绍了其工作原理(和示例) .
如果您想要的是一个单一数据库表,那么您应该使用代理模型,但是它们确实不允许您创建新字段。该字段应该在父模型中创建,或者以其他方式存在于数据库中,根本不由 Django 迁移处理。
关于python - 继承模型更新到其父模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57593894/