英文:
Django MySQL UUID
问题
我有一个 Django 模型字段,在默认的 SQLite 数据库中工作正常:
```uuid = models.TextField(default=uuid.uuid4, editable=False, unique=True)```。
然而,当我尝试迁移到 MySQL 时,我遇到了错误:
```django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'uuid' used in key specification without a key length")```。
我尝试的第一件事是移除 ```unique=True```,但是我得到了相同的错误。接下来,因为我有另一个字段(成功迁移):
```id = models.UUIDField(default=uuid.uuid4, editable=False)```
我尝试将 uuid 更改为 UUIDField,但仍然遇到相同的错误。最后,我将 uuid 更改为:
```uuid = models.TextField(editable=False)```
但是在迁移时我仍然得到相同的错误(删除所有表,makemigrations,migrate --run-syncdb)。理想情况下,我想要一个带有 default=uuid.uuid4、editable=False 和 unique=True 的 UUIDField 或 TextField,但是在创建对象时在视图中执行这些任务也可以。
英文:
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.
答案1
得分: 1
你需要为你的 UUID 字段设置 max_length
。由于 UUID v4 使用 36 个字符,你可以将其设置为 max_length=36
(确保数据库中没有更长的值):
uuid = models.TextField(default=uuid.uuid4, editable=False, unique=True, max_length=36)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论