Django 1.8'default'选项只能执行一次外部功能 [英] Django 1.8 'default' option only executes external function once
问题描述
我正在尝试向现有表添加一个 UUID
字段。我指定了 default = uuid.uuid4
但是,Django似乎并没有每个都调用 uuid.uuid4
函数行。所以当我迁移我不断得到重复的uuid错误。
I am trying to add a UUID
field to an existing table. I specified that default = uuid.uuid4
however, it Django doesn't seem to call uuid.uuid4
function for every row. So when I migrate I keep getting duplicated uuid error.
我的 Django
版本是 1.8.2
/ p>
My Django
version is 1.8.2
.
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('conv', '0008_video_video_uri'),
]
operations = [
migrations.AddField(
model_name='conversation',
name='channel_id',
field=models.UUIDField(unique=True, default=uuid.uuid4, editable=False),
),
]
下面的错误:
> > File "/home/yonk/projects/trailerapp/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py",
> line 64, in execute
> return self.cursor.execute(sql, params) django.db.utils.IntegrityError: could not create unique index
> "conv_conversation_channel_id_68f7d58df7c78d61_uniq" DETAIL: Key
> (channel_id)=(5f512cbe-e514-4bf5-bf5a-3efd1a94e401) is duplicated.
推荐答案
这里你有django文档描述你想要的:
https:// docs.djangoproject.com/en/1.8/howto/writing-migrations/#migrations-that-add-unique-fields
Here you have django docs describing exactly what you want: https://docs.djangoproject.com/en/1.8/howto/writing-migrations/#migrations-that-add-unique-fields
您将需要两次迁移文件。
You will need two migration files.
- 首先添加字段,也可以将unique = True更改为null = True,因此django不会尝试使用默认值...
- 第二次迁移填充该字段。
所以第二次迁移应该如下所示:
So second migration should look like this:
def gen_uuid(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
for row in MyModel.objects.all():
row.uuid = uuid.uuid4()
row.save()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0004_add_uuid_field'),
]
operations = [
# omit reverse_code=... if you don't want the migration to be reversible.
migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
]
这篇关于Django 1.8'default'选项只能执行一次外部功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!