viviwill
viviwill

Reputation: 1573

Django migrate after adding foreign key gives "unknown column" error

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)

I'm using mysql. After adding the foreignkey, the makemigrations command is working. The python manage.py migrate command will give the error:

  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'")

The python manage.py sqlmigrate dash 0004 gives:

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;

Upvotes: 0

Views: 1114

Answers (1)

Aviah Laor
Aviah Laor

Reputation: 3658

hmm, It seems like a bug. Django converts the agent field to a foreign key, before it committed the new agent field. It starts with ALTER TABLE ... CHANGE, before it actually added the field.

Try to add the field in two steps:

  1. Add an IntegerField agent field (not as foreign key), makemigrations, migrate
  2. Change agent from integer field to foreign key, makemigrations, migrate

Consider to open a django ticket for this issue.

Upvotes: 2

Related Questions