执行python manage.py migrate时触发ValueError: invalid literal for int() with base 10错误求助
ValueError: invalid literal for int() with base 10: 'SOME STRING' During Django Migration Hey there, let's break down why this error is happening and how to fix it! That error pops up when Django tries to convert a string value ('SOME STRING') into an integer for your first_team_score or second_team_score fields—since those are defined as IntegerField in your GameScore model.
Common Causes
- Model Field Type Change: You probably had one (or both) of the score fields set to
CharFieldearlier, then switched toIntegerField—but your database still has old string values like'SOME STRING'stored. - Broken Migration File: A recent migration might have an invalid default value (like a string instead of an integer) for the Integer fields, or a data migration step that incorrectly assigns strings to these fields.
Step-by-Step Solutions
1. Check Your Migration History & Model Changes
First, head to your app's migrations folder and look at the recent migration files. Look for any AlterField operations that changed a CharField to IntegerField for first_team_score or second_team_score. That's almost certainly where the problem started.
2. Fix Existing Database Data (If You Need to Keep It)
If your database has important data, you'll need to clean up the invalid string values first:
- Rollback to the last working migration: Run
python manage.py migrate <your_app_name> <migration_number_before_the_change>(replace placeholders with your app name and the last migration that worked, like0002_previous_migration). - Update the bad data: Access your database (via a tool like phpMyAdmin, pgAdmin, or Django shell) and set any
'SOME STRING'values in the score fields to a valid integer (like0).- Example using Django shell:
python manage.py shellfrom yourapp.models import GameScore # Fix first_team_score GameScore.objects.filter(first_team_score='SOME STRING').update(first_team_score=0) # Fix second_team_score GameScore.objects.filter(second_team_score='SOME STRING').update(second_team_score=0)
- Example using Django shell:
- Re-run migrations: Now run
python manage.py migrateagain—it should work since the invalid strings are gone.
3. Fix a Broken Migration File
If the issue is in your migration file itself (like a wrong default value):
- Open the problematic migration file and check for lines like:
field=models.IntegerField(default='SOME STRING'), - Change the default value to an integer (e.g.,
default=0), then save the file and re-runpython manage.py migrate.
4. Use a Data Migration for Safe Field Type Conversion
If you need to convert existing string scores to integers automatically (instead of manually editing the database), create a data migration:
- Generate an empty migration file:
python manage.py makemigrations --empty <your_app_name> - Open the new migration file and replace its contents with this (update placeholders like
<your_app_name>):from django.db import migrations def convert_scores_to_integers(apps, schema_editor): GameScore = apps.get_model('<your_app_name>', 'GameScore') for game in GameScore.objects.all(): # Fix first_team_score try: game.first_team_score = int(game.first_team_score) except (ValueError, TypeError): game.first_team_score = 0 # Fix second_team_score try: game.second_team_score = int(game.second_team_score) except (ValueError, TypeError): game.second_team_score = 0 game.save() class Migration(migrations.Migration): dependencies = [ ('<your_app_name>', '<last_valid_migration_number>'), ] operations = [ migrations.RunPython(convert_scores_to_integers), migrations.AlterField( model_name='gamescore', name='first_team_score', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='gamescore', name='second_team_score', field=models.IntegerField(default=0), ), ] - Run the migration:
python manage.py migrate
Quick Fix for Dev Environments (Data Doesn't Matter)
If you're in development and don't care about losing existing data, you can:
- Delete your database file (e.g.,
db.sqlite3for SQLite) - Delete all migration files except
__init__.pyin your app'smigrationsfolder - Run
python manage.py makemigrationsthenpython manage.py migrateto start fresh.
内容的提问来源于stack exchange,提问作者menna

