2

I have this model in my Django project:

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

I run my project completely when I use SQLite ,but when I change my database engine to Mysql I got this error:

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

What I must to do?

rahnama7m
  • 865
  • 10
  • 38
  • I had `unique=True,` in my `name` field and when I delete that, Error has been gone, But I don't know the reason! – rahnama7m Jul 12 '19 at 10:58
  • 1
    See here for an explanation :-): https://stackoverflow.com/questions/1827063/mysql-error-key-specification-without-a-key-length – RaideR Jul 12 '19 at 11:25

1 Answers1

0

I got this error because I was trying to create an index for a TextField. I didn't notice I had used TextField for my name field, I was supposed to use CharField.

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

Here was my solution.

First, I deleted the migration file created when I added an index in my model for the first time and run python manage.py makemigrations

Second, I removed the index from my model.

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

Third, I run python manage.py makemigrations. It showed "no changes detected".

Fourth, I run python manage.py migrate and I did not get the error again.

To successfully create the index, I had to change the TextField field to CharField and add the index again.

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

Running makemigrations and migrate went fine and created the index successfully.

Stanley Ulili
  • 702
  • 5
  • 7