Django在添加外键后进行迁移"未知列"错误

时间:2016-02-25 01:44:51

标签: mysql django migrate

class Agent(models.Model):
    full_name = models.CharField(max_length=200)
    short_code = models.CharField(max_length=200)

class Phone(models.Model):
    date = models.DateTimeField('Call Time')
    ...
    // Newly added:
    agent = models.ForeignKey(Agent, on_delete=models.CASCADE)

我正在使用mysql。添加外键后,makemigrations命令正在运行。 python manage.py migrate命令将给出错误:

  File "/Library/Python/2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute
    return self.cursor.execute(query, args)
  File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
django.db.utils.OperationalError: (1054, "Unknown column 'agent' in 'dash_phone'")

python manage.py sqlmigrate dash 0004给出:

BEGIN;
--
-- Alter field agent on phone
--
ALTER TABLE `dash_phone` CHANGE `agent` `agent_id` integer NOT NULL;
ALTER TABLE `dash_phone` MODIFY `agent_id` integer NOT NULL;
CREATE INDEX `dash_phone_agent_id_e9e1c068_uniq` ON `dash_phone` (`agent_id`);
ALTER TABLE `dash_phone` ADD CONSTRAINT `dash_phone_agent_id_e9e1c068_fk_dash_agent_id` FOREIGN KEY (`agent_id`) REFERENCES `dash_agent` (`id`);

COMMIT;

1 个答案:

答案 0 :(得分:2)

嗯,这似乎是一个bug。 Django在提交新代理字段之前将代理字段转换为外键。在实际添加字段之前,它以ALTER TABLE ... CHANGE开头。

尝试分两步添加字段:

  1. 添加IntegerField代理字段(不是外键),makemigrations,migrate
  2. 将代理从整数字段更改为外键,makemigrations,迁移
  3. 考虑为此问题打开一张django票。