Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django migration with uuid field generates duplicated values

I have a uuid field (not a primary key). The generated migration is:

from __future__ import unicode_literals  from django.db import migrations, models import uuid   class Migration(migrations.Migration):      dependencies = [         ....     ]      operations = [         ...         migrations.AddField(             model_name='device',             name='uuid',             field=models.UUIDField(default=uuid.uuid4, unique=True),         ),         ...     ] 

But when doing python manage.py migrate it is crashing with:

django.db.utils.IntegrityError: could not create unique index "restaurants_device_uuid_key" DETAIL: Key (uuid)=(f3858ded-b8e0-4ac0-8436-8a61b10efc73) is duplicated.

Strangely enough, the problem does not seem to occur with primary keys (which are maybe created by the database, and not internally by django?)

How can I add a uuid field, and make sure that migrations work?

like image 611
blueFast Avatar asked Feb 08 '16 23:02

blueFast


People also ask

What is the use of UUID field in Django?

UUIDField is a special field to store universally unique identifiers. It uses Python's UUID class. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids.

What is difference between migrate and Makemigrations in Django?

makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.


1 Answers

Here is an example doing everything in one single migration thanks to a RunPython call.

# -*- coding: utf-8 -* from __future__ import unicode_literals  from django.db import migrations, models import uuid   def create_uuid(apps, schema_editor):     Device = apps.get_model('device_app', 'Device')     for device in Device.objects.all():         device.uuid = uuid.uuid4()         device.save()   class Migration(migrations.Migration):      dependencies = [         ('device_app', 'XXXX'),     ]      operations = [         migrations.AddField(             model_name='device',             name='uuid',             field=models.UUIDField(blank=True, null=True),         ),         migrations.RunPython(create_uuid),         migrations.AlterField(             model_name='device',             name='uuid',             field=models.UUIDField(unique=True)         )     ] 
like image 99
v.thorey Avatar answered Oct 19 '22 07:10

v.thorey