数据库:mysql
原model
class testModel(models.Model)
test = models.CharField(max_length=32)
修改后的model
class testModel(models.Model)
test_pk = models.CharField(max_length=32, primary_key=True)
test = models.CharField(max_length=32)
自动生成的migrations大概是这样:
operations=[
migrations.AddField(
model_name='testModel',
name='test_pk',
field=models.CharField(max_length=30, serialize=False, primary_key=True),
preserve_default=False,
)
]
用自动生成的migrations来migrate有时会mysql会出现重复的主键错误
解决办法:
修改上面这段代码,先添加一个普通的字段,然后使用migrations.RunSQL来给更新主键的值,最后再修改这个字段成主键。
operations=[
migrations.AddField(
model_name='testModel',
name='test_pk',
field=models.CharField(max_length=30, serialize=False),
preserve_default=False,
),
migrations.RunSQL("update table set test_pk = test;"),
migrations.AlterField(
model_name='testModel',
name='test_pk',
field=models.CharField(max_length=30, serialize=False, primary_key=True),
preserve_default=False,
),
]
然后就可以正常进行migrate操作。
本文地址:http://my.oschina.net/soarwilldo/blog/686571