我当前的项目使用multi-table inheritance models:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class Cinema(Place):
sells_tickets = models.BooleanField(default=False)
sells_popcorn = models.BooleanField(default=False)
我想换成abstract base classes。由于我的模型已经部署,我需要编写一些自定义迁移来将上述模式转换为此模式:
from django.db import models
class AbstractPlace(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Meta:
abstract = True
class Restaurant(AbstractPlace):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class Cinema(AbstractPlace):
sells_tickets = models.BooleanField(default=False)
sells_popcorn = models.BooleanField(default=False)
有人对实现这一目标的步骤有什么建议吗
我最近解决了这个问题,我通过在下面的代码块中编写和运行迁移来解决这个问题——松散地进行翻译以适合您的案例中的模型
我非常确定,不可能直接更改旧
Restaurant
和Cinema
模型的表,因为如果您尝试向它们添加字段,它们将与基础模型的现有字段冲突,并且如果您尝试通过手动设置基础模型的options
将派生模型与基础模型“解耦”,例如,Django报告说,它无法找到Restaurant
和Cinema
的基本模型。(据我所知,这些问题可能是由错误引起的。)为了避免这个问题,我为派生模型创建了新表,将数据从旧表复制到新表,删除旧表,并重命名新表以匹配旧表的名称我从Django生成的代码中获得了下面的大部分代码,可以通过创建一个临时迁移(在使用下面的代码创建之前)来复制它,该迁移只删除
Restaurant
、Cinema
和Place
,运行makemigrations
,并复制CreateModel()
和AlterField()
(对于指向Restaurant
或Cinema
的相关字段)从生成的迁移作为记录,我使用的是Django3.1.4
请注意,我最初编写的迁移仅在使用SQLite时进行了测试;其他数据库管理系统可能不接受如此大量的迁移操作,您可能必须将其拆分为多个迁移。(我有点不确定到底是什么导致了这个问题,但我记得我在PostgreSQL中也遇到过这种情况。)
请让我知道这是否解决了您的问题!😊
相关问题 更多 >
编程相关推荐