Search code examples
djangodatabasepostgresqldjango-modelsdjango-migrations

Migrate a PositiveIntegerField to a FloatField


I have an existing populated database and would like to convert a PositiveIntegerField into a FloatField. I am considering simply doing a migration:

    migrations.AlterField(
        model_name='mymodel',
        name='field_to_convert',
        field=models.FloatField(
            blank=True,
            help_text='my helpful text',
            null=True),
    ),

Where the field is currently defined as:

field_to_convert = models.PositiveIntegerField(
    null=True,
    blank=True,
    help_text='my helpful text')

Will this require a full rewrite of the database column? How well might this conversion scale for larger databases? How might it scale if the vast majority values were null? In what circumstances would this conversion fail? This is a backed by a Postgres database if that makes a difference.


Solution

  • Will this require a full rewrite of the database column?

    No, it won't. I did an experiment with PostgreSQL, MySQL, and SQLite the conversion from integer to float goes well in every case, I also put some values as null to match your situation.

    If you have a value 3, it just will change to 3.0.

    How might it scale if the vast majority values were null?

    Well, since you keep null=True in the configuration of your field all null values will remain null, no problem with that. If you remove null=True you might need to specify a default value.

    In what circumstances would this conversion fail?

    Taking an int column and converting it to float (real) should not fail, if you find a bizarre, weird and very special case it would be a very big finding.

    If you have doubts about the migration outcome...

    ... you can first take a look into migrations SQL with sqlmigrate, and of course, you could backup your database.