Django migrations.AddField中外键的默认值 [英] Default value for foreign key in Django migrations.AddField

查看:576
本文介绍了Django migrations.AddField中外键的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用迁移,我需要添加一个新字段(外国键)到模型。我知道这可以做到:
$ b $ $ p $ migrations.AddField(
model_name ='MyModel',
name ='state',
field = models.ForeignKey(null = True,related_name ='mymodel_state',to ='msqa_common.MyModelState'),
),

但是,我不希望我的字段为空。相反,我想为它使用一个默认值,对应于名称为available的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

解决方案

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


Using migrations, I need to add a new field (a foreign key) to a model. I know it can be done with:

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

However, I don't want my field to be nullable. Instead, I want to use a default value for it, corresponding to the id of MyModelState whose name is "available" (id value might change in different machines). This "available" value of table MyModelState is inserted into the database in a previous migration script, so it does exist.

I guess I should do something like:

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

My question: How can I get the available_state_id within my migration script?

解决方案

You can't do it directly. The recommended way of doing this is to create a migration to add it with null=True, then add a data migration that uses either Python or SQL to update all the existing ones to point to available_state_id, then a third migration that changes it to null=False.

这篇关于Django migrations.AddField中外键的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆