尝试将 CharField 数据中的数据迁移到表格中的 FloatingField 。新的floatingField具有Null = True。 在python manage.py migrate之后。我得到 ValueError:无法将字符串转换为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
答案 0 :(得分:1)
您必须自己在迁移中进行转换:
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()