pythondjangoormdjango-ormschema-migration

Django ORM migration giving "ValueError: invalid literal for int()" on IntegerField


Step by step, here is how I got to where I am now...

I attempted ran the command python manage.py migrate after changing my Order table in my database to include include flowertype = IntegerField() and was told that I couldn't move forward with the migration until I either a) set a default value to the IntegerField(), or b) let django set it for me. I chose a and set the default value to 'something' just to get the error out of my hair.

Realizing that I shouldn't have put a string into an IntegerField(), I have tried the following to fix this issue.

1) tried to reset models.IntegerField() to models.IntegerField(default='1')

2) tried to reset my sql database using django-reset and it gave me a ton of errors like `ImportError: cannot import name sql_delete

3) commenting out my Order model and then running makemigrations & migrate to no avail.


Solution

  • The migration failed in python, so it never made it to the database. You should leave everything as is, and go into the migrations/ folder and delete the migration which adds the flowertype field (it's going to be the most recent one). Then run python manage.py makemigrations again, but make sure you have flowertype = IntegerField(default=1) (not default='1') set in the model definition.

    EDIT for further explanation:

    When you run the command makemigrations, django inspects all of your model definitions in python and compares them against what is in the database. If the two don't match, django will create a migration file which will update the database to reflect the model definitions as they are defined in your python code. This is what the migrate command does, it runs all of the new migration files.

    So the first time you ran makemigrations, a migration file was created which added a column to the Order table, and tried to set the value of every row to 'something'.

    This immediately failed, since it was trying to put a str into and int field.

    Since it failed, unless you delete the file, any and everytime you run migrate, django was going to keep trying to run that script. There were two options 1) You could've just went in and edited the migration file by hand, or 2) You can just delete that migration file and re-create it once you have your model definitions fixed.