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

时间:2019-03-19 10:17:33

标签: 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')

我正在使用Django 1.11.3和postgreSQL。

迁移成功,默认值为一个。

错误堆栈-

Env details

error

error

谢谢。

2 个答案:

答案 0 :(得分:1)

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)

然后使用data migration用所需的值填充字段:

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),
    ]

,然后从字段中删除null=True

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

答案 1 :(得分:1)

步骤1.将 null=True 添加为 tech_lead 字段,

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', null=True)

第2步。通过 python manage.py makemigrations

创建迁移文件 步骤3.迁移数据库 python manage.py migrate

步骤4.打开django shell, python manage.py shell

步骤5.运行以下脚本

from your_app.models import Application
from django.db.models.expressions import F

Application.objects.filter(tech_lead__isnull=True).update(tech_lead=F('assessment_owner'))