Django South - 将外键更改为必需

时间:2013-12-30 17:23:40

标签: django postgresql django-south

我改变了我的模型:

class DistList(models.Model):
   creator = models.ForeignKey(User, related_name='creator')
   created_date = models.DateTimeField(auto_now_add=True)
   name = models.CharField(max_length=200, unique=True)
   description = models.TextField(blank=True, null=True)
   company = models.ForeignKey(Company, blank=True, null=True)

对此:

class DistList(models.Model):
   creator = models.ForeignKey(User, related_name='creator')
   created_date = models.DateTimeField(auto_now_add=True)
   name = models.CharField(max_length=200, unique=True)
   description = models.TextField(blank=True, null=True)
   company = models.ForeignKey(Company)

唯一的变化是将公司FK关系从不需要变为必需。

当我运行迁移时,我指定一个与第一家公司的pk相对应的一个关闭值。

./manage.py schemamigration distlist --auto 
? The field 'DistList.company' does not have a default specified, yet is NOT NULL.
? Since you are making this field non-nullable, you MUST specify a default
? value to use for existing rows. Would you like to:
?  1. Quit now, and add a default to the field in models.py
?  2. Specify a one-off value to use for existing columns now
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> 1

但是当我运行迁移时,我收到一个错误,因为它有一个挂起的触发事件?

./manage.py migrate distlist 
Running migrations for distlist:
- Migrating forwards to 0005_auto__chg_field_distlist_company.
> distlist:0005_auto__chg_field_distlist_company
FATAL ERROR - The following SQL query failed: ALTER TABLE "distlist_distlist" ALTER COLUMN "company_id" SET NOT NULL;
The error was: cannot ALTER TABLE "distlist_distlist" because it has pending trigger events

从我的角度来看,我没有做任何看起来很奇怪的事情,所以我根本不理解这个错误。有人能提供见解吗?我可以发布完整的堆栈跟踪,如果它会有所帮助,但我觉得有一些关于南方和postgresql的明显的东西,也许我错过了?

1 个答案:

答案 0 :(得分:0)

所以我相信我找到了答案。我认为postgresql不喜欢同时改变模式和添加数据。我首先创建了一个数据迁移:

 ./manage.py datamigration distlist add_default_values_to_existing_companies

然后我将其添加到前锋方法中:

  def forwards(self, orm):
    "Write your forwards methods here."
    for distlist in orm['distlist.Distlist'].objects.all():
        distlist.company = orm['userprofile.Company'].objects.get(id=1)
        distlist.save()

然后我改变了模型以从公司中移除空白和null。

然后我运行了模式迁移并选择为值指定一个为1(就像我在问题中所做的那样)。

然后我编辑了那个迁移文件:

def forwards(self, orm):

    # Changing field 'DistList.company'
    # db.alter_column(u'distlist_distlist', 'company_id', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['userprofile.Company']))
    db.alter_column(u'distlist_distlist', 'company_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['userprofile.Company']))

我只是注释掉了生成的行并删除了默认值= 1 arg。

我不知道......也许这不对,但似乎有效。希望这会对某人有所帮助。