You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行python manage.py migrate时触发ValueError: invalid literal for int() with base 10错误求助

Fixing 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 CharField earlier, then switched to IntegerField—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, like 0002_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 (like 0).
    • Example using Django shell:
      python manage.py shell
      
      from 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)
      
  • Re-run migrations: Now run python manage.py migrate again—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-run python 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:

  1. Generate an empty migration file:
    python manage.py makemigrations --empty <your_app_name>
    
  2. 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),
            ),
        ]
    
  3. 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.sqlite3 for SQLite)
  • Delete all migration files except __init__.py in your app's migrations folder
  • Run python manage.py makemigrations then python manage.py migrate to start fresh.

内容的提问来源于stack exchange,提问作者menna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:06:45