为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森林海 2021-12-09 15:42:38
我最近开始使用 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。使用一次性默认值迁移成功。错误堆栈 -
查看完整描述

2 回答

?
翻阅古今

TA贡献1780条经验 获得超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),

    ]

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


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


查看完整回答
反对 回复 2021-12-09
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

步骤 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)

Step 2. create migration file by Step 3. migrate the db Step 4. open django shell, Step 5. 运行以下脚本python manage.py makemigrations


python manage.py migrate


python manage.py shell



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



查看完整回答
反对 回复 2021-12-09
  • 2 回答
  • 0 关注
  • 265 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号