0

I had a django model field which was working in the default sqlite db:

uuid = models.TextField(default=uuid.uuid4, editable=False, unique=True).

However, when I tried to migrate to MySQL, I got the error:

django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'uuid' used in key specification without a key length")

The first thing I tried was removing the unique=True, but I got the same error. Next, since I had another field (which successfully migrated ):

id = models.UUIDField(default=uuid.uuid4, editable=False)

I tried changing uuid to UUIDField, but I still get the same error. Finally, I changed uuid to:

uuid = models.TextField(editable=False)

But I am still getting the same error when migrating (DROP all the tables, makemigrations, migrate --run-syncdb). Ideally, I want to have a UUIDField or TextField with default = uuid.uuid4, editable = False, and unique = True, but I am fine doing these tasks in the view when creating the object.

Randusr
  • 39
  • 6

1 Answers1

1

You need to set max_length for your uuid field. Since UUID v4 uses 36 charactes, you can set it to max_length=36 (make sure you don't have longer values in the db already):

uuid = models.TextField(default=uuid.uuid4, editable=False, unique=True, max_length=36)
Marco
  • 2,371
  • 2
  • 12
  • 19
  • I just tried this, getting the same error. – Randusr Feb 18 '23 at 23:46
  • How do you "migrate" to the new db? – Marco Feb 18 '23 at 23:50
  • I do python manage.py dbshell, then I do DROP TABLE for each of the tables in my app, then I exit and do python manage.py makemigrations, and python manage.py migrate --run-syncdb. – Randusr Feb 18 '23 at 23:52
  • Why do you drop tables when you migrate to a new database? It should be empty? And do you remove the old migration files? Since you use migrations, you don't need `--run-syncdb` (https://stackoverflow.com/questions/29683494/what-should-i-use-instead-of-syncdb-in-django-1-9). I recommend using an `UUIDField` in the new database anyway. – Marco Feb 19 '23 at 00:01
  • I drop the tables because if not I get a different error (https://stackoverflow.com/questions/75494608/django-mysql-table-already-exists) . I tried with UUIDField as well, but same error, but that seems weird, because I don't think UUIDField is considered BLOB/TEXT type. – Randusr Feb 19 '23 at 00:07
  • I think you have trouble with your migrations. If I get you right just do the following: 1. make sure you have a fresh database without any tables 2. remove ALL your migrations files 3. generate migrations file with `makemigrations` 4. migrate to your new db with `migrate` – Marco Feb 19 '23 at 00:14