python - Django 1.8 'default' option only executes external function once -


i trying add uuid field existing table. specified default = uuid.uuid4 however, django doesn't seem call uuid.uuid4 function every row. when migrate keep getting duplicated uuid error.

my django version 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),         ),     ] 

below error:

> >  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: not create unique index > "conv_conversation_channel_id_68f7d58df7c78d61_uniq" detail:  key > (channel_id)=(5f512cbe-e514-4bf5-bf5a-3efd1a94e401) duplicated. 

here have django docs describing want: https://docs.djangoproject.com/en/1.8/howto/writing-migrations/#migrations-that-add-unique-fields

you need 2 migration files.

  1. first 1 adds fields, change unique=true null=true django won't try use default value...
  2. second migration populates field.

so second migration should this:

def gen_uuid(apps, schema_editor):     mymodel = apps.get_model('myapp', 'mymodel')     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 don't want migration reversible.         migrations.runpython(gen_uuid, reverse_code=migrations.runpython.noop),     ] 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -