Skip to main content
 首页 » 编程设计

python之南 : updating boolean field

2025年05月04日11lautakyan007

假设我有这个模型:

class Knight(models.Model): 
    name = models.CharField(max_length=100) 
    of_the_round_table = models.BooleanField() 

然后说我想把它改成这样:

class Knight(models.Model): 
    name = models.CharField(max_length=100) 
    round_table = models.BooleanField() 

schemamigration southtut --auto --update 之后,South 提示我不可避免的事情:

 ? The field 'Knight.of_the_round_table' does not have a default specified, yet is NOT NULL. 
 ? Since you are adding this field, you MUST specify a default 
 ? value to use for existing rows. Would you like to: 
 ?  1. Quit now, and add a default to the field in models.py 
 ?  2. Specify a one-off value to use for existing columns now 
 ? Please select a choice: 2 
 ? Please enter Python code for your one-off default value. 
 ? The datetime module is available, so you can do e.g. datetime.date.today() 
 >>> "True" 

最后,当我尝试使用 ./manage.py migrate someapp 进行迁移时,我收到了:

ValueError: invalid literal for int() with base 10: 'True' 

不太确定为什么“True”不正确。我相信我尝试不带括号输入它,它也给出了。我在这里做错了什么?我应该如何输入默认值?

编辑: 附加问题 - 为什么 south 还要求我为以前的每个迁移输入一个值?如果我再次迁移并将“round_table”的名称更改为“table”,它会要求我为“of_the_round_table = models.BooleanField( )”、“round_table = models.BooleanField()”和“table = models.BooleanField()”。为什么?它不应该只要求最新的吗?无论如何可以使这个过程更快?如果您过去进行过多次迁移,我可以看出这是一种痛苦。

请您参考如下方法:

  1. "True" 不是 bool 值,它是字符串。使用 True。

  2. 南方不仅可以向前迁移,也可以向后迁移。如果向后迁移,它需要知道将什么值放入"new"列 of_the_round_table。仅在非空字段上指定默认值或更好地将迁移定义为 rename_column 而不是删除一列并添加另一列(就像 auto 为您所做的那样)可能更容易。