如何修复 'Argument must be a string' TypeError

How to fix 'Argument must be a string' TypeError

我有一个元组,我正尝试将其用于模型中的选择字段。 虽然,我创建的 table 没有我现在尝试添加的最后一列(可选值 - 可以为空)。 这是我的模型代码

class SemesterData(models.Model):
  YESNOCHOICE = (
     ('Y', 'Yes'),
    ('N', 'No'),
  )
   sid = models.ForeignKey(SessionData,on_delete=models.CASCADE)
   semester_name = models.CharField(max_length=50)
   status = models.CharField(max_length=3, choices=YESNOCHOICE, null=True, default=YESNOCHOICE[1][0])

    def __str__(self):
        return self.semester_name

我的堆栈跟踪显示

C:\Users\BOLADE\Desktop\django-project\clearance>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, system
Running migrations:
  Applying system.0002_auto_20190109_1729...Traceback (most recent call las
t):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\__init__.py", line 381, in execute_
from_command_line
    utility.execute()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\base.py", line 316, in run_from_arg
v
    self.execute(*args, **cmd_options)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\core\management\commands\migrate.py", line 203, in
handle
    fake_initial=fake_initial,
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, f
ake_initial=fake_initial)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_a
ll_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=
fake_initial)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\migrations\executor.py", line 244, in apply_migr
ation
    state = migration.apply(state, schema_editor)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, p
roject_state)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\migrations\operations\fields.py", line 216, in d
atabase_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\backends\base\schema.py", line 523, in alter_fie
ld
    old_db_params, new_db_params, strict)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\backends\base\schema.py", line 626, in _alter_fi
eld
    old_default = self.effective_default(old_field)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\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 (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\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=Fa
lse)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\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 (x86)\Microsoft Visual Studio\Shared\Python36_64\l
ib\site-packages\django\db\models\fields\__init__.py", line 1807, in get_pr
ep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number
, not 'tuple'

我在 Django 2.1 和 Python 3.6 中使用 MySQL 5。我已经在这个平台上尝试过之前的建议,但仍然显示相同的错误。

失败的迁移

# Generated by Django 2.1.4 on 2019-01-09 16:29

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('system', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='semesterdata',
            name='status',
            field=models.CharField(choices=[('Y', 'Yes'), ('N', 'No')], default='N', max_length=3),
        ),
    ]

0001_initial.py # 由 Django 2.1.4 于 2019-01-08 生成20:00

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='DepartmentData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('dept_name', models.CharField(max_length=50)),
                ('created_on', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.CreateModel(
            name='FacultyData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('faculty_name', models.CharField(max_length=30)),
                ('created_on', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.CreateModel(
            name='SemesterData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('semester_name', models.CharField(max_length=50)),
                ('status', models.IntegerField(choices=[('0', 'Yes'), ('1', 'No')], default=('1', 'No'))),
            ],
        ),
        migrations.CreateModel(
            name='SessionData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('session_name', models.CharField(max_length=15)),
            ],
        ),
        migrations.AddField(
            model_name='semesterdata',
            name='sid',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='system.SessionData'),
        ),
        migrations.AddField(
            model_name='departmentdata',
            name='fid',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='system.FacultyData'),
        ),
    ]

尝试使用model_utils.Choices。它更具可读性,你可以避免你的错误

from django.db import models
from model_utils import Choices


class SemesterData(models.Model):
    YESNOCHOICE = Choices(
        (0, 'yes', 'Yes'),
        (1, 'no', 'No'),
    )

    sid = models.ForeignKey(SessionData, on_delete=models.CASCADE)
    semester_name = models.CharField(max_length=50)
    status = models.IntegerField(choices=YESNOCHOICE, default=YESNOCHOICE.no)

初始迁移中的默认值不正确。

default=('1', 'No')

改为

default=1

请注意,您需要进行数据迁移才能将数据库中任何现有的 10 值更改为 'Y' 或 'N'。

如果您刚刚开始您的项目并且您的数据库中没有任何您需要的数据,您可能会发现最简单的方法是删除数据库,删除两个迁移,然后重新运行 makemigrations 和迁移。