Django:将新的外键添加到现有模型,默认值作为同一模型中的另一个外键

Pri*_*nka 2 python django postgresql foreign-keys

我最近开始使用 Django,所以请耐心等待。我有一个有 2 个外键的模型

class Application(models.Model): assessment_owner = models.ForeignKey(User, related_name='assessment_owner') creator = models.ForeignKey(User, related_name='creator')

我正在尝试将名为 tech_lead 的新外键添加到同一模型中,tech_lead 的默认值应该是assessment_owner。稍后,我可以使用数据加载更新 tech_lead 的值,但最初它应该是评估所有者。

通过以下代码片段,Django 在进行迁移时要求默认值,并在各处分配相同的 tech_lead。我想通过代码定义 tech_lead 的默认值,简单的默认属性不起作用。我尝试使用信号 pre_save 和 post_save 但没有成功。

class Application(models.Model):
    assessment_owner = models.ForeignKey(User, related_name='assessment_owner')
    creator = models.ForeignKey(User, related_name='creator')
    tech_lead = models.ForeignKey(User, related_name='tech_lead')
Run Code Online (Sandbox Code Playgroud)

我正在使用 Django 1.11.3 和 postgreSQL。

迁移成功并具有一次性默认值。

错误堆栈 -

环境详情

错误

错误

提前致谢。

Kyr*_*nko 5

tech_lead = models.ForeignKey(User, related_name='tech_lead')

破坏完整性,因为您的数据库已经填充了Application实例。如果你想在你的方案中添加一个不可为空的 FK,你应该指定默认值。否则,如果无法提供默认值,则应考虑允许tech_lead为 NULL,即:

tech_lead = models.ForeignKey(User, related_name='tech_lead', null=True)

然后使用数据迁移用您想要的值填充字段:

from django.db import migrations

def populate_tech_lead(apps, schema_editor):
    Application = apps.get_model('yourappname', 'Application')
    for application in Application.objects.all():
        application.tech_lead = application.assessment_owner
        application.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(populate_tech_lead),
    ]
Run Code Online (Sandbox Code Playgroud)

然后null=True从现场删除:

tech_lead = models.ForeignKey(User, related_name='tech_lead')

  • 您可以通过 3 次迁移来完成。创建可为空字段=>创建[数据迁移](https://docs.djangoproject.com/en/2.1/topics/migrations/#data-migrations)以更新字段值=>使字段不可为空 (2认同)