2016-02-12 106 views
1

试图从数据迁移CharField数据到FloatingField在一个表中。新的floatingField有Null = True。 python manage.py migrate.I得到ValueError:无法将字符串转换为浮点数: 迁移文件如下所示。Django数据迁移类型转换问题

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.Since值它们都是coordinates.Some领域得到了空值well.How可我把它保存在table.Database FloatingField列的Postgres

回答

1

你要做的转换自己在迁移:

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

注意,如果你有一个是空或包含空字符串或字符串,它是不是一个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() 
+0

得到还曾为: 的餐厅Restaurant.objects.all(): 如果restaurant.lat: restaurant.lat_duplicate = restaurant.lat 如果restaurant.lng: restaurant.lng_duplicate =餐厅。 lng restaurant.save() –