我遇到了还原包含重命名表的Django(1.8.7)迁移的问题。即使它似乎能够在Postgres中重命名它,它然后尝试使用旧表名添加约束。
这是追溯:
[...]
ALTER TABLE "team_membershiprole" RENAME TO "team_leadershiprole";
[...]
ALTER TABLE "team_leadershipteammember"
ADD CONSTRAINT "team_l_role_id_xxx"
FOREIGN KEY ("role_id") REFERENCES "team_membershiprole" ("id")
DEFERRABLE INITIALLY DEFERRED;
[...]
COMMIT;
如果你看一下它生成的SQL,
team_membershiprole
您可以看到有# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0023_xxx'),
('team', '0009_xxx2'),
]
operations = [
migrations.CreateModel(
name='TeamMembership',
fields=[
('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),
('team', models.ForeignKey(related_name='members', to='team.Team')),
('member', models.ForeignKey(to='core.Member')),
],
),
migrations.RenameModel(
old_name='LeadershipRole',
new_name='MembershipRole',
),
migrations.RemoveField(
model_name='leadershipteammember',
name='team',
),
migrations.RemoveField(
model_name='leadershipteammember',
name='member',
),
migrations.RemoveField(
model_name='leadershipteammember',
name='role',
),
migrations.DeleteModel(
name='LeadershipTeamMember',
),
migrations.AddField(
model_name='teammembership',
name='role',
field=models.ForeignKey(to='team.MembershipRole'),
),
]
的引用,即使该表不再存在(它已重命名)。这是迁移代码:
belongs_to :company
counter_culture :company, :column_name => Proc.new {|user| user.active? ? 'users_count' : nil }
我知道这可能是一个Django迁移错误,但是有什么方法可以解决它吗?
答案 0 :(得分:1)
您可以覆盖Migration.unapply,以便它使用一组不同的操作。
class MyMigration(Migration):
operations = [
... your operations ...
]
reverse_operations = [
... your fixed reverse operations ...
]
def unapply(self, project_state, schema_editor, collect_sql=False):
self.operations = self.reverse_operations
return super(MyMigration, self).unapply(..)
我没有测试过这个,但它应该给你一个想法。哦,您可能需要反转反向迁移列表,因为Django会期望它是正向迁移的列表,因此反向遍历它们。