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')
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'))
添加回答
举报
