首页 > 解决方案 > 我可以从 django ForeignKey 中删除 null=True 参数吗?

问题描述

我有两个模型,foobar。它们已经存在于我的数据库中,每个都有很多实例。现在,我意识到应该添加一个关系。因此,我希望在foo和之间添加一个 ForeignKey bar

class foo():
  # lots of stuff
  bar = models.ForeignKey(bar, related_name='foo', null=True)

我实际上不希望密钥可以为空,但由于它们已经存在,我需要添加它,因为需要填充现有行。

null=True一旦所有实例都填充了 foreignKey 字段,我可以稍后删除该参数吗?

标签: pythondjango

解决方案


Yes you can, basically to reach this you need to do three steps

  1. Create a first migration, where you create your field as nullable
  2. Create a second migration to populate already existing fields
  3. Create a third migration where you set the field as not nullable

A very good step by step is explained here


推荐阅读