Reputation: 1573
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
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:
Consider to open a django ticket for this issue.
Upvotes: 2