我有一个遗留数据库,其int index设置为10位数。我需要Django迁移来创建我的forigen键到int(10)而不是int(11)
默认情况下,Django Forigenkey设置int(11),当试图让Mysql中的ForigenKeys给出错误时:
django.db.utils.OperationalError: (1005, 'Can\'t create table `test_table`.`#sql-169_1ec` (errno: 150 "Foreign key constraint is incorrectly formed")')
我尝试在模型中使用“validators = [MaxValueValidator(9999999999)]”,它将迁移转换为:
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='clients.Customer', validators=[django.core.validators.MaxValueValidator(9999999999)]),
但是当django迁移创建整数字段时,它使用int(11)
创建任何线索如何修改int的长度?
我的模特:
class Customer(models.Model):
... (BUNCH OF FIELDS HERE)....
django_user = models.ManyToManyField(User, through= 'CustomerUser')
class Meta:
db_table = 'customers'
class CustomerUser(models.Model):
ROL_USUARIO = (
('T', 'Tecnico'),
('G', 'Gerente'),
('E', 'Emplead'),
)
cliente = models.ForeignKey(Customer, null= True, validators=[MaxValueValidator(9999999999)])
usuario = models.ForeignKey(User, null= True)
rol = models.CharField(choices=ROL_USUARIO, max_length = 1, null= True, default='')
迁移:
migrations.CreateModel(
name='CustomerUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rol', models.CharField(choices=[('T', 'Tecnico'), ('G', 'Gerente'), ('E', 'Emplead')], default='', max_length=1, null=True)),
**intentionally skipped**
#('cliente', models.ForeignKey(null=True,on_delete=django.db.models.deletion.DO_NOTHING, to='clients.Customer')),
#('usuario', models.ForeignKey(null=True,on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='customeruser',
name='cliente',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='clients.Customer', validators=[django.core.validators.MaxValueValidator(9999999999)]),
),
最后一个提示错误:“外键约束错误形成”
答案 0 :(得分:2)
您可以选择使用int(10)
创建forigenKey。通过编辑空的迁移文件。
首先使用
创建空的迁移文件python manage.py makemigrations --empty myapp
然后编辑operations = []
以使用forigenKey int(10)执行rawsql
您的新迁移文件:
class Migration(migrations.Migration):
dependencies = [
('myapp', '0009_auto_20160623_xxxxx'),
]
operations = [
migrations.RunSQL("ALTER TABLE myapp_table MODIFY field_id int(10);")
]