Run python Django example
To customize nullable previously set to null.
models.py
python
import uuid
class MyEntity(Model):
name = CharField(max_length=100, unique=True)
code = CharField(
max_length=100,
unique=True,
null=True,
blank=True,
)
def save(self, *args, **kwargs):
if not self.code:
self.code = f"{self.name}_{uuid.uuid4()}"
return super().save(*args, **kwargs)
And now to apply this change to existing data, you can create a custom migration.
0002_custom_migration.py
python
from django.db import migrations, models
def forwards_func(apps, schema_editor):
from myaapp.models import MyEntity
db_alias = schema_editor.connection.alias
entities = MyEntity.objects.using(db_alias).filter(code=None)
for entity in entities:
entity.save()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_mypreviousmigration'),
]
operations = [
migrations.RunPython(
forwards_func, reverse_code=migrations.RunPython.noop
),
]