gpt4 book ai didi

python - Django 从字符字段迁移到整数字段?

转载 作者:行者123 更新时间:2023-12-03 21:18:30 25 4
gpt4 key购买 nike

我在models.py 中更改了我的CharField 之一:

models.CharField(max_length=128, blank=True)

进入 IntegerField -->
models.IntegerField(default=0)

我有该字段的数据,主要是空字符串( "" )或整数作为字符串(例如: "10" )。

所以我想在迁移时将这些字符串转换为整数。例如::
如果空白字符串( "" ) 转换为 0 , 否则转换为整数。

我怎样才能做到这一点,而我这样做 ./manage.py migrate命令?

这是使用 ./manage.py makemigrations 创建的迁移文件::
# Generated by Django 2.1.2 on 2018-10-25 04:57

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('dashboard', '0002_auto_20181024_1544'),
]

operations = [
migrations.AlterField(
model_name='aclpermissions',
name='ordering',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='submenus',
name='ordering',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='subsubmenus',
name='ordering',
field=models.IntegerField(default=0),
),
]

当我运行时 ./manage.py migrate我有错误::
psycopg2.DataError: invalid input syntax for integer: ""

因为有空字符串的字段 "" .

所以我想将空字符串( "" )转换为 0 .

最佳答案

对于遇到此问题的其他人,您可以添加一个在其他迁移操作之前运行的函数:

class Migration(migrations.Migration):

def blank_to_zero(apps, schema_editor):
AclPermissions = apps.get_model('dashboard', 'AclPermissions')
SubMenus = apps.get_model('dashboard', 'SubMenus')
SubSubMenus = apps.get_model('dashboard', 'SubSubMenus')

for obj in AclPermissions.objects.filter(ordering=''):
obj.ordering = 0
obj.save()

for obj in SubMenus.objects.filter(ordering=''):
obj.ordering = 0
obj.save()

for obj in SubSubMenus.objects.filter(ordering=''):
obj.ordering = 0
obj.save()

dependencies = [
('dashboard', '0002_auto_20181024_1544'),
]

operations = [
migrations.RunPython(blank_to_zero),

migrations.AlterField(...
# the rest of your operations
]
https://docs.djangoproject.com/en/dev/topics/migrations/#data-migrations有关编辑数据迁移的信息。

关于python - Django 从字符字段迁移到整数字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com