Reputation: 181
I need to add slug field to django model, and i thing it's better when it not null. So i'm trying to add slug to model
slug = models.SlugField(
'URL',
unique=True,
default=id_generator,
)
my id_generator:
import string
import random
def id_generator():
size=16
chars=string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for x in range(size))
The problem is when i migrate changes. Method id_generator is calling one time and uses the same value for all model objects. So i have dupliicate entrie in unique field. How can i generate unique values? Django 1.11.5
P.S. I understand, that i can set null=True and customize model's save method to add slug when saving.
Upvotes: 4
Views: 1828
Reputation:
MOST IMPORTANT: You have not good generator for unique slug, may be best way use uuid for example
import uuid
slug = models.CharField(max_length=64, blank=True, unique=True, default=uuid.uuid4)
example first step migration, replace YOUMODEL:
from __future__ import unicode_literals
import string
import random
from django.db import migrations, models
def id_generator():
size=16
chars=string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for x in range(size))
def update_slug(pp, schema_editor):
for instance in YOUMODEL.objects.all():
# ^^^^^^^
instance.slug = id_generator()
instance.save()
class Migration(migrations.Migration):
operations = [
migrations.AddField(
model_name='YOUMODEL',
# ^^^^^^^
name='slug',
field=models.SlugField(null=True, verbose_name='URL'),
),
migrations.RunPython(code=update_slug)
]
Upvotes: 1