【问题标题】:First migration to a new PostgreSQL database. ValueError: invalid literal for int() with base 10: ''第一次迁移到新的 PostgreSQL 数据库。 ValueError: int() 以 10 为底的无效文字:''
【发布时间】:2025-11-25 10:45:01
【问题描述】:

拥有已成功使用 SQLite 数据库的 models.py。现在尝试使用 PostgreSQL。如果您查看 Traceback,似乎整数字段有一个字符串默认值。我只是看不到它。评论了大部分字段,进行了迁移,仍然是同样的问题。

追溯

 Operations to perform:
  Apply all migrations: admin, auth, contenttypes, players, sessions, silk, users
Running migrations:
  Applying players.0007_auto_20190130_1427...Traceback (most recent call last):
  File "D:\temp\YandexDisk\programming\py\nhl_web_app\manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "c:\program files\python37\lib\site-packages\django\core\management\__init__.py",
 line 381, in execute_from_command_line
    utility.execute()
  File "c:\program files\python37\lib\site-packages\django\core\management\__init__.py",
 line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin
e 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin
e 353, in execute
    output = self.handle(*args, **options)
  File "c:\program files\python37\lib\site-packages\django\core\management\base.py", lin
e 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "c:\program files\python37\lib\site-packages\django\core\management\commands\migr
ate.py", line 203, in handle
    fake_initial=fake_initial,
  File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l
ine 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=f
ake_initial)
  File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l
ine 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)

  File "c:\program files\python37\lib\site-packages\django\db\migrations\executor.py", l
ine 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "c:\program files\python37\lib\site-packages\django\db\migrations\migration.py",
line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)

  File "c:\program files\python37\lib\site-packages\django\db\migrations\operations\fiel
ds.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "c:\program files\python37\lib\site-packages\django\db\backends\base\schema.py",
line 523, in alter_field
    old_db_params, new_db_params, strict)
  File "c:\program files\python37\lib\site-packages\django\db\backends\postgresql\schema
.py", line 122, in _alter_field
    new_db_params, strict,
  File "c:\program files\python37\lib\site-packages\django\db\backends\base\schema.py",
line 627, in _alter_field
    new_default = self.effective_default(new_field)
  File "c:\program files\python37\lib\site-packages\django\db\backends\base\schema.py",
line 239, in effective_default
    return field.get_db_prep_save(default, self.connection)
  File "c:\program files\python37\lib\site-packages\django\db\models\fields\__init__.py"
, line 790, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "c:\program files\python37\lib\site-packages\django\db\models\fields\__init__.py"
, line 785, in get_db_prep_value
    value = self.get_prep_value(value)
  File "c:\program files\python37\lib\site-packages\django\db\models\fields\__init__.py"
, line 1807, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

模型.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
from players.storage import OverwriteStorage


class Player(models.Model):
    name = models.CharField(max_length=128, default='nme')
    nhl_id = models.IntegerField(unique=True, default=25)
    slug = models.SlugField()
    # image = models.ImageField(upload_to='players_pics', storage=OverwriteStorage(), max_length=None)
    # team = models.CharField(max_length=128, default='')
    # position = models.CharField(max_length=128, default='')
    # height = models.CharField(max_length=128, default='')
    # weight = models.IntegerField(default=25)
    # birth_date = models.CharField(max_length=128, default='')
    # birth_city = models.CharField(max_length=128, default='')
    # birth_state = models.CharField(max_length=128, default='')
    # birth_country = models.CharField(max_length=128, default='')
    # nation = models.CharField(max_length=128, default='')
    # draft_year = models.CharField(max_length=128, default='')
    # draft_number = models.CharField(max_length=128, default='')
    # games = models.IntegerField(default=25)
    # pl_number = models.IntegerField(null=True, default=25)
    # age = models.IntegerField(null=True, default=25)
    # roster_status = models.CharField(max_length=128, default='')
    # captain = models.BooleanField(default=False)
    # alt_captain = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.name}'

    def save(self, *args, **kwargs):
        is_new = self.pk is None
        if is_new:
            self.slug = slugify(self.name)
        super(Player, self).save(*args, **kwargs)

    class Meta:
        abstract = True


class Skater(Player):
    # favorite = models.ManyToManyField(User, related_name='favorite_s', blank=True)
    goals = models.IntegerField(default=10)
    # goals_avg = models.FloatField(default=10)
    # assists = models.IntegerField()
    # assists_avg = models.FloatField(default=10)
    # points = models.IntegerField()
    # points_avg = models.FloatField(default=10)
    # plus_minus = models.IntegerField()
    # plus_minus_avg = models.FloatField(default=10)
    # penalty_min = models.IntegerField()
    # penalty_min_avg = models.FloatField(default=10)
    # shots = models.IntegerField()
    # shots_avg = models.FloatField(default=10)
    # hits = models.IntegerField(null=True)
    # hits_avg = models.FloatField(default=10, null=True)
    # blocks = models.IntegerField(null=True)
    # blocks_avg = models.FloatField(default=10, null=True)
    # faceoff_wins = models.IntegerField(null=True)
    # faceoff_wins_avg = models.FloatField(default=10, null=True)
    # pp_points = models.IntegerField()
    # pp_points_avg = models.FloatField(default=10)
    # sh_points = models.IntegerField()
    # sh_points_avg = models.FloatField(default=10)
    # time_on_ice = models.CharField(max_length=128, default='')
    # time_on_ice_pp = models.CharField(max_length=128, default='')
    # time_on_ice_sh = models.CharField(max_length=128, default='')


class Goalie(Player):
    # favorite = models.ManyToManyField(User, related_name='favorite_g', blank=True)
    wins = models.IntegerField(default=10)
    # losses = models.IntegerField()
    # ot_losses = models.IntegerField()
    # goals_against_av = models.FloatField()
    # saves_perc = models.FloatField()
    # saves = models.IntegerField()
    # shotouts = models.IntegerField()

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'nhl_web_app_1',
        'USER': 'postgres',
        'PASSWORD': '***',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

【问题讨论】:

  • 请提供0007_auto_20190130_1427.py迁移文件的内容
  • @awesoon,你说得对。我只是无法正确阅读回溯。没想到它会尝试应用旧的迁移文件。删除了所有迁移,现在无法应用新的初始迁移。它的意思是“没有要申请的迁移”
  • 你也回滚数据库了吗?如果这是没有任何生产数据的本地数据库,您可以通过指定要应用的最新迁移 (docs.djangoproject.com/en/2.1/ref/django-admin/…) 进行回滚,使用原始 DDL 手动回滚,或者只是删除并重新创建数据库。
  • migrate 不知道新旧迁移,它只知道应用了哪些迁移,默认情况下它会尝试应用所有未应用的迁移。所有应用的迁移都存储在django_migrations 表中。

标签: python django database python-3.x postgresql


【解决方案1】:

在@awesoon 的帮助下,我找到了错误。

问题出在迁移文件0007_auto_20190130_1427.py

我有一个 IntegerField - default='' 的字符串默认值

migrations.AlterField(
    model_name='skater',
    name='time_on_ice_pp',
    field=models.IntegerField(default='', null=True),
),

需要将此默认值替换为任意整数。

migrations.AlterField(
    model_name='skater',
    name='time_on_ice_pp',
    field=models.IntegerField(default=10, null=True),
),

【讨论】: