python - Django 1.8 'default' 选项只执行一次外部函数

标签 python django

我正在尝试将 UUID 字段添加到现有表中。我指定了 default = uuid.uuid4 但是,Django 似乎并没有为每一行调用 uuid.uuid4 函数。因此,当我迁移时,我不断收到重复的 uuid 错误。

我的 Django 版本是 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

您将需要两个迁移文件。

  1. 第一个添加字段,还将 unique=True 更改为 null=True 这样 django 就不会尝试使用默认值...
  2. 第二次迁移填充该字段。

所以第二次迁移应该是这样的:

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),
    ]

关于python - Django 1.8 'default' 选项只执行一次外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30927563/

相关文章:

python - 子进程在使用多处理时不考虑参数

jquery - 使用 jquery 的 ajax 调用中未设置 HTTP_X_REQUESTED_WITH

python - 如何设置 django 在单元测试期间不使用内存数据库?

python - Matplotlib 等同于 ggplot geom_ribbon?

python - python RSA中相同 key 的不同解密输出

python - 根据条件将数据框列拆分为不同的列

python - Django 名称模式未在 ulrs.py 中定义

Django 模板 : get total iteration count for nested loops

在 url 中使用点的 Django Rest Framework

python - 在 Django 测试框架中使用 Basic HTTP 访问认证