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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lancegentry/article/details/90906675

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就可以了

展开阅读全文

没有更多推荐了,返回首页