我正在使用Django 1.9.5和python 2.7。我也使用MySQL作为数据库。当我尝试进行迁移时,出现以下错误
“无法添加外键约束”
我在尝试将多个字段添加到现有表时收到此错误。当我进行迁移和迁移时,将创建多对多关系表,但没有外键约束。
在运行服务器时,它还会说;
“您有未应用的迁移;在应用之前,您的应用可能无法正常运行。”
运行“ python manage.py migration”以应用它们。我可以通过网站将新数据添加到该表中,但没有外键约束。但是我需要使用外键约束为关系创建表字段。该操作将在Worker表和Workerduty表之间创建多对多关系。MySQL已配置为InnoDB。
代码如下:
models.py :
class Workerduty(BaseModel):
name = models.CharField(max_length=50, unique=True, verbose_name=_("Worker Duty"))
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class Worker(BaseModel):
duty_type = models.ManyToManyField(Workerduty, verbose_name=_("Worker Duty"))
name = models.CharField(max_length=100, db_index=True, verbose_name=_("Name"))
class Meta:
permissions = (
("Workerl", _("Workerl")),
)
ordering = ['name']
def __unicode__(self):
return "%s %s" % (self.name)
def save(self, *args, **kwargs):
self.name = self.name.title()
grps = []
for Workerduty_obj in self.Workerduty.all():
grp = Group.objects.get_or_create(name=Workerduty_obj.name)[0]
grps.append(grp)
self.user.grps = grps
self.user.save()
super(Worker, self).save(*args, **kwargs)
迁移文件:
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2018-06-28 20:09
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('company', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Workerduty',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False, verbose_name='Unique Identifier')),
('name', models.CharField(max_length=50, unique=True, verbose_name='Worker Duty')),
],
options={
'ordering': ['name'],
},
),
慕桂英4014372
相关分类