2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
tech_lead = models.ForeignKey(User, related_name='tech_lead')
破壞完整性,因?yàn)槟臄?shù)據(jù)庫已經(jīng)填充了Application實(shí)例。如果你想在你的方案中添加一個(gè)不可為空的 FK,你應(yīng)該指定默認(rèn)值。否則,如果您不能提供默認(rèn)值,則應(yīng)考慮允許tech_lead為 NULL,即:
tech_lead = models.ForeignKey(User, related_name='tech_lead', null=True)
然后使用數(shù)據(jù)遷移用您想要的值填充字段:
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貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
步驟 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. 運(yùn)行以下腳本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'))
添加回答
舉報(bào)