我有這樣一個模型(簡化了相關性):如何安全地從模型中刪除ForeignKey字段?
class Director(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
user_account = models.ForeignKey(User, null=True, blank=True)
我剛剛意識到user_account
必須OneToOneField
,而不是ForeignKey
。進行這種改變基本上意味着刪除現有的user_account
字段和創建新的。
問題是,我在過去糟糕的經驗,當與ForeignKey
字段混淆。更糟的是,我已經在數據庫中創建了一對Director
對象,ForeignKey
鏈接到User
對象。
我的問題是如何刪除並最終更改user_account
字段而不會導致運行時錯誤?
其他上下文:我正在使用Django 1.9和PostgreSQL。
當你說「創建一個數據遷移」,你的意思是像'migrations.RunPython()'? – vleong
https://docs.djangoproject.com/en/1.9/topics/migrations/#data-migrations –
很好的答案。這是我爲將來參考所做的遷移(https://gist.github.com/vleong2332/612fa933ffff8aa64063) – vleong