gpt4 book ai didi

Django South - 将外键更改为必需

转载 作者:行者123 更新时间:2023-11-29 14:00:33 26 4
gpt4 key购买 nike

我改变了我的模型:

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

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

最佳答案

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

 ./manage.py datamigration distlist add_default_values_to_existing_companies

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

  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()

然后我修改了模型,从 company 中删除了空白和 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']))

我刚刚注释掉了生成的行并删除了 default=1 arg。

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

关于Django South - 将外键更改为必需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com