Python 2 -> 3 Django迁移导致字段参数类型改变

Python 2 -> 3 Django migration causes field parameter type change

我们正在运行从 Django 1.8 -> 2.1 和 Python 2.7 -> 3.6 定位 Django 项目。

在旧的项目版本中,有这样的Django模型,例如:

# models.py

from django.db import models

class RowStatusModel(models.Model):
    active = models.BooleanField(default=True, db_column='is_active')
    # ...
    class Meta:
        abstract = True

请注意,此模块中使用的 from __future__ import unicode_literals 而不是 。也就是说 db_column 是一个 Python 2 str,对应 Python 3 中的 bytes。初始迁移,0001_initial.py,看起来像这样:

# 0001_initial.py

operations = [
    # ...
    ('row_ef', models.BooleanField(default=True, db_column=b'is_active')
    # ...
]

注意字节文字 b'is_active,我想这是 Django 为了更明确的目的而完成的,但我不确定。

现在,在 t运行 将大部分代码库与 2to3 和 运行 makemigrations、Python 相结合后,Python 3 将字符串文字视为 unicode 类型Python 2,因此生成一个迁移,其中 db_column 是一个字符串文字,对于每个继承自 RowStatusModel:

的模型
# migrations/0023_auto_20180827_1955.py 
migrations.AlterField(
    # ...
    field=models.BooleanField(default=True, db_column='is_active')
), # ...

./manage.py migrate 为运行 时,如果有,这对数据库端有什么影响? "change" 纯粹是在 Python 方面,还是会产生什么副作用?


数据库引擎是 django.db.backends.postgresql


我知道如果 migrate 导致直接问题,我们可以只克隆 RDS 实例并恢复到该实例,但我更担心引入的更微妙的问题,这些问题要等到很多时候才会被发现稍后。

我在问了这个问题后遇到了 Django ticket,Django 开发人员的建议是编辑任何包含 (Python 的遗留迁移文件(例如 0001_initial) 3) 字节文字,删除 b 并使它们成为 Python 中的字符串文字 3.

Editing migrations to fix this issue is safe.

从那里你应该能够删除使用 python3 ./manage.py makemigrations 制作的迁移模块,然后重做该命令,这应该不再与该参数的类型有关。

我使用以下方法将 'db_column=b' 的所有实例批量查找并替换为 'db_column='。当然,您应该在提交之前绝对检查 git diff

grep -nrl "db_column=b" apps | xargs sed -i "s/db_column=b/db_column=/g"