Reputation: 1077
I added a new uuid field to my table, user_table, with existing rows. Due to a race condition I am getting the "Duplicate entry" error when migrating. I then followed the steps here:
http://django.readthedocs.org/en/latest/howto/writing-migrations.html
Now my first and second migrations run but my last migrations gives me the same error. My 3 migrations per the link are as follows:
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('app', '0008_label'),
]
operations = [
migrations.AddField(
model_name='user_table',
name='UUID_loc',
field=models.UUIDField(default=uuid.uuid4, null=True),
),
migrations.AlterField(
model_name='another_table',
name='Time',
field=models.CharField(default=0, max_length=3),
),
]
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
def gen_uuid(apps, schema_editor):
MyModel = apps.get_model('app', 'user_table')
for row in MyModel.objects.all():
row.uuid = uuid.uuid4()
row.save()
class Migration(migrations.Migration):
dependencies = [
('app', '0009_label'),
]
operations = [
# omit reverse_code=... if you don't want the migration to be reversible.
migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
]
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('app', '0010_label'),
]
operations = [
migrations.AlterField(
model_name='user_table',
name='UUID_loc',
field=models.UUIDField(default=uuid.uuid4, unique=True),
),
]
The link was very relevant to me but unfortunately I am getting the same error. Now I am stuck here where my tables have the UUID_loc field, but it is not unique yet, i.e. the third migration isn't run yet. Can anyone please provide some insight? Thank you.
Upvotes: 3
Views: 2320
Reputation: 1194
I think you should to slightly edit your second migration to prevent django from updating your models with duplicate uuid values.
def gen_uuid(apps, schema_editor):
MyModel = apps.get_model('app', 'user_table')
for row in MyModel.objects.all():
while True:
row.uuid = uuid.uuid4()
if not MyModel.objects.filter(uuid=row.uuid).exists():
break
row.save()
The you should re-run your second migration again and then you should be able to run third migration without any problems.
Upvotes: 3