Django migrations.AddField中外键的默认值

时间:2016-03-29 09:24:21

标签: django foreign-keys default django-migrations

使用migrations,我需要向模型添加一个新字段(外键)。我知道可以通过以下方式完成:

    migrations.AddField(
        model_name='MyModel',
        name='state',
        field=models.ForeignKey(null=True, related_name='mymodel_state', to='msqa_common.MyModelState'),
    ),

但是,我不希望我的字段可以为空。相反,我想使用它的默认值,对应于名称为"可用"的MyModelState的id。 (id值可能会在不同的机器中更改)。这"可用"表的值MyModelState在先前的迁移脚本中插入到数据库中,因此它确实存在。

我想我应该这样做:

    migrations.AddField(
        model_name='MyModel',
        name='state',
        field=models.ForeignKey(null=False, default=available_state_id, related_name='mymodel_state', to='msqa_common.MyModelState'),
    ),

我的问题:如何在迁移脚本中获取available_state_id

2 个答案:

答案 0 :(得分:19)

你不能直接这样做。建议的方法是创建迁移以使用null = True添加它,然后添加使用Python或SQL更新所有现有的数据迁移以指向available_state_id,然后进行第三次迁移将其更改为null = False。

答案 1 :(得分:0)

我只是遇到了同样的问题,偶然发现了这个答案,所以这是我的做法:

  operations = [
        # We are forced to create the field as non-nullable before
        # assigning each Car to a Brand
        migrations.AddField(
            model_name="car",
            name="brand",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                to="model.Brand",
            ),
        ),

        # assign_car_to_brand loops over all my Car objects and sets their
        # "brand" field
        migrations.RunPython(add_category_to_tags, do_nothing),

        # Make the field non-nullable to force all future Car to have a Brand
        migrations.AlterField(
            model_name="car",
            name="brand",
            field=models.ForeignKey(
                null=False,
                on_delete=django.db.models.deletion.PROTECT,
                to="model.Brand",
            ),
            preserve_default=False
        ),

    ]
相关问题