【问题标题】:"BLOB/TEXT column used in key specification without a key length" error in DjangoDjango中的“密钥规范中使用的BLOB / TEXT列没有密钥长度”错误
【发布时间】:2019-07-12 10:09:07
【问题描述】:

我的 Django 项目中有这个模型:

class Institution(models.Model):
    name = models.CharField(unique=True, max_length=100, blank=True)
    description = models.TextField(max_length=500, null=True, blank=True)        
    def __str__(self):
        return self.name

当我使用 SQLite 时,我完全运行了我的项目,但是当我将我的数据库引擎更改为 Mysql 时,我收到了这个错误:

MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'name' used in key specification without a key length")

我必须做什么?

【问题讨论】:

标签: python django django-models django-2.2 django-mysql


【解决方案1】:

我收到此错误是因为我试图为 TextField 创建索引。我没有注意到我在name 字段中使用了TextField,我应该使用CharField

class myModel(models): 
    name = models.TextField(max_length=80)
   
    class Meta:                                                                                                                              
        indexes = [ models.Index(fields=['name'])]

这是我的解决方案。

首先,我删除了我第一次在模型中添加索引时创建的迁移文件并运行python manage.py makemigrations

其次,我从模型中删除了索引。

class myModel(models): 
    name = models.TextField(max_length=80)

第三,我运行python manage.py makemigrations。它显示“未检测到变化”。

第四,我运行python manage.py migrate并没有再次收到错误。

要成功创建索引,我必须将TextField 字段更改为CharField 并再次添加索引。

class myModel(models): 
    name = models.CharField(max_length=80)
   
    class Meta:                                                                                                                              
        indexes = [ models.Index(fields=['name'])]

运行makemigrationsmigrate 运行良好并成功创建索引。

【讨论】:

    【解决方案2】:

    解决方法很简单,按照他们的步骤操作即可。

    1 - Dell all the files in the migration folder
    2 - Then run the command "python manage.py makemigrations"
    3 - Then run the command "python manage.py migrate"
    

    借助简单的 SQL-lite 查询来完成 添加索引示例

    alter table test 添加索引 index_name(col1(255),col2(255));

    添加唯一索引示例

    alter table test add unique index_name(col1(255),col2(255));

    【讨论】:

    • 在删除文件夹 django.db.migrations.exceptions.NodeNotFoundError: Migration dialogs.0003_auto_20200606_1943 依赖项引用不存在的父节点('bot_manager','0002_auto_20200606_1803')后无法正常工作
    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多