我对Django开发还是个新手。我正在使用一个用MySQL创建的遗留数据库。现在我面临着Django迁移的问题。我很少有表使用外键来引用另一个表。现在,如果我允许Django管理那些带有外键的表,那么Django将尝试在make-migrations和migrate命令期间重新创建外键字段。即使田地已经在那里。此外,如果我不允许Django管理这些表,Django可以完美地处理数据库。
我的代码是针对表面对错误的from django.db import models
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import pre_save
from chooseright.utils import unique_slug_generator
class StoreTable(models.Model):
store_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=45, blank=True, null=True)
slug = models.SlugField(max_length=45, blank=True, null=True)
catagory = models.ForeignKey(CatagoryTable, on_delete=models.CASCADE, blank=True, null=True)
brand = models.ForeignKey(BrandTable, models.DO_NOTHING, blank=True, null=True)
class Meta:
managed = True
db_table = 'store_table'
verbose_name = _("Store")
verbose_name_plural = _("Stores")
def __str__(self):
return self.namefrom django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20200820_1258'),
]
operations = [
migrations.RenameField(
model_name='storetable',
old_name='store_name',
new_name='name',
),
migrations.AddField(
model_name='storetable',
name='brand',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.BrandTable'),
),
migrations.AddField(
model_name='storetable',
name='catagory',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.CatagoryTable'),
),
]File "C:\Users\Usama\dev\Django Projects\lib\site-packages\MySQLdb\connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1060, "Duplicate column name 'brand_id'")
现在我知道Django正在尝试重新创建外键字段。但既然是遗留数据库,我就不能理解为什么会发生这种情况。