我正在将现有数据库导入到它自己的 Django 项目中。我已经从数据库中生成了初始模型,通过,并且使 Django 通过注释表元设置中inspectdb
的行来一次控制每个表。managed=False
我从简单的模型开始,在启用带有外键的表时遇到了麻烦。Django 不断为外键生成相同的迁移,DocTagID
我不确定它为什么这样做?
有问题的表如下所示,inspectdb
除了注释行之外,所有内容都是由生成的,这是我将表的控制权传递给 Django 的地方。
class Doctagversion(models.Model):
id = models.IntegerField(db_column='Id', primary_key=True, blank=True) # Field name made lowercase.
doctagid = models.ForeignKey(DocTag, models.DO_NOTHING, db_column='DocTagId') # Field name made lowercase.
groupname = models.TextField(db_column='GroupName') # Field name made lowercase.
name = models.TextField(db_column='Name') # Field name made lowercase.
creationdate = models.DateTimeField(db_column='CreationDate') # Field name made lowercase.
lasteditdate = models.DateTimeField(db_column='LastEditDate', blank=True, null=True) # Field name made lowercase.
lastedituserid = models.IntegerField(db_column='LastEditUserId') # Field name made lowercase.
lastedituserdisplayname = models.TextField(db_column='LastEditUserDisplayName') # Field name made lowercase.
releasedate = models.DateTimeField(db_column='ReleaseDate', blank=True, null=True) # Field name made lowercase.
class Meta:
# managed = False
db_table = 'DocTagVersion'
在传递此控制之前,使用 生成相关架构的初始迁移python -m manage.py makemigrations
,并使用python -m manage.py migrate
. 表的初始迁移如下,managed
设置为False
最初,注释行是我相信我应该添加的一个条目,以通知 Django 外键(inspectdb
在生成中的状态一样多models.py
)。
migrations.CreateModel(
name='Doctagversion',
fields=[
('id', models.IntegerField(blank=True, db_column='Id', primary_key=True, serialize=False)),
# ('doctagid',models.ForeignKey(db_column='DocTagId', default=-1, on_delete=models.deletion.DO_NOTHING, to='DocTag')),
('groupname', models.TextField(db_column='GroupName')),
('name', models.TextField(db_column='Name')),
('creationdate', models.DateTimeField(db_column='CreationDate')),
('lasteditdate', models.DateTimeField(blank=True, db_column='LastEditDate', null=True)),
('lastedituserid', models.IntegerField(db_column='LastEditUserId')),
('lastedituserdisplayname', models.TextField(db_column='LastEditUserDisplayName')),
('releasedate', models.DateTimeField(blank=True, db_column='ReleaseDate', null=True)),
],
options={
'db_table': 'DocTagVersion',
'managed': False,
},
),
当我启用对表的控制时,第一次迁移只会更改表选项。
migrations.AlterModelOptions(
name='doctagversion',
options={},
),
如果初始迁移中不存在外键,Django 会添加有问题的外键,如下所示。
migrations.AddField(
model_name='doctagversion',
name='doctagid',
field=models.ForeignKey(db_column='DocTagId', default=-1, on_delete=django.db.models.deletion.DO_NOTHING, to='docutoo.DocTag'),
preserve_default=False,
),
此后,它重复生成以下迁移作为 和 之间的一个python m manage.py makemigrations
循环python -m manage.py migrate
。
migrations.AlterField(
model_name='doctagversion',
name='doctagid',
field=models.ForeignKey(db_column='DocTagId', on_delete=django.db.models.deletion.DO_NOTHING, to='docutoo.DocTag'),
),
也许我的策略是错误的,我应该在一次迁移中简单地启用所有表?
据我所知,以下相关问题不能说明我的情况: