2016-02-12 101 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() –