Anand VL
Anand VL

Reputation: 13

Django data migration Type conversion Issue

Tried for data migration from CharField data into FloatingField in a table.The New floatingField have Null=True. After python manage.py migrate.I got ValueError: could not convert string to float: Migration file looks like this.

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 have values like 10.787878.Since they all are coordinates.Some fields got null values as well.How could i save it in FloatingField column in table.Database is postgres

Upvotes: 1

Views: 542

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

You have to do the conversion by yourself in the migration:

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

Note that if you have fields that are NULL or contains an empty string or a string that is not an acceptable representation of a float, you will have to properly handle these cases:

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()

Upvotes: 1

Related Questions