Django 报错 django.db.utils.OperationalError: (1071, 'Specified key was too long) 解决方法

Django 报错 django.db.utils.OperationalError: (1071, ‘Specified key was too long; max key length is 767 bytes’)

如果出现以下形式的报错, 则是因为模型的CharFieldmax_length指定的过大。可以通过直接修改migrations的文件修复。

  File "/home/yyy/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query
    db.query(q)
  File "/home/yyy/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')

例如下面的代码是原文件

class Migration(migrations.Migration):

    dependencies = [
        ('goods', '0006_remove_goodstype_order'),
    ]

    operations = [
        migrations.AlterField(
            model_name='goodstype',
            name='name',
            field=models.CharField(max_length=256, unique=True, verbose_name='名称'),
        ),
    ]

修改为:

class Migration(migrations.Migration):

    dependencies = [
        ('goods', '0006_remove_goodstype_order'),
    ]

    operations = [
        migrations.AlterField(
            model_name='goodstype',
            name='name',
            
            # 修改这里的max_length为50
            field=models.CharField(max_length=50, unique=True, verbose_name='名称'),
        ),
    ]

修改后不要忘记修改对应的模型,执行migrate就可以了

你可能感兴趣的:(Django)