【问题标题】:How to fix 'Argument must be a string' TypeError如何修复“参数必须是字符串”类型错误
【发布时间】:2019-01-09 16:39:08
【问题描述】:

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

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'

我将 MySQL 5 与 Django 2.1 和 Python 3.6 一起使用。我已经在这个平台上尝试过以前的建议,但仍然显示同样的错误。

失败的迁移

# 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'),
        ),
    ]

【问题讨论】:

  • 提供完整的堆栈跟踪
  • 这里不是出错的地方,请贴回溯(以及相关视图等)
  • 可能您的视图有一个“tailing comma”,这样您就不会将模型对象或主键传递给 ORM 调用,而是包含此类模型的元组对象或主键。
  • @WillemVanOnsem 我已编辑问题以包含完整的堆栈跟踪
  • 请显示失败的迁移0002_auto_20190109_1729。

标签: mysql django python-3.x tuples django-2.1


【解决方案1】:

尝试使用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)

【讨论】:

  • 显示错误 django.db.utils.OperationalError: (1366, "Incorrect integer value: '' for column 'status' at row 1")
  • @AkinniyiBodeBolade 我已经确定了答案,现在检查一下
  • 这很好用。但是有没有办法在模板中将值设为“是”而不是“Y”
  • @AkinniyiBodeBolade 你需要更新Choices 对象,我改了答案
【解决方案2】:

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

default=('1', 'No')

改成

default=1

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2020-12-01
    • 2021-06-02
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多