gpt4 book ai didi

python - Django 数据迁移类型转换问题

转载 作者:行者123 更新时间:2023-11-29 13:25:01 25 4
gpt4 key购买 nike

尝试将数据从 CharField 数据迁移到表中的 FloatingField。新的 floatingField 有 Null=True。在 python manage.py migrate.I 得到 ValueError: could not convert string to float:迁移文件如下所示。

def coordinates(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Restaurant = apps.get_model("foodspots", "Restaurant")
for restaurant in Restaurant.objects.all():
restaurant.lat_duplicate = restaurant.lat
restaurant.lng_duplicate = restaurant.lng
restaurant.save()


class Migration(migrations.Migration):

dependencies = [
('foodspots', '0028_auto_20160211_1931'),
]

operations = [
migrations.RunPython(coordinates),
]

CharFields 的值类似于 10.787878。因为它们都是坐标。有些字段也有空值。我如何将它保存在表的 FloatingField 列中。数据库是 postgres

最佳答案

您必须在迁移中自己进行转换:

for restaurant in Restaurant.objects.all():       
restaurant.lat_duplicate = float(restaurant.lat)
restaurant.lng_duplicate = float(restaurant.lng)
restaurant.save()

请注意,如果您的字段为 NULL 或包含空字符串或不是可接受的 float 表示形式的字符串,您将必须正确处理这些情况:

for restaurant in Restaurant.objects.all():       
# minimalistic error handling
try:
restaurant.lat_duplicate = float(restaurant.lat)
restaurant.lng_duplicate = float(restaurant.lng)
except (TypeError, ValueError) as e:
print "invalid type or value for restaurant %s : %s" % (
restaurant, e
)
else:
restaurant.save()

关于python - Django 数据迁移类型转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364073/

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