Django Migrations Add Field with Default as Function of Model

I just learned how to do this with a single migration! When running makemigrations django should ask you to set a one-off default. Define whatever you can here to keep it happy, and you’ll end up with the migration AddField you mentioned. migrations.AddField( model_name=”series”, name=”updated_as”, field=models.DateTimeField(default=????, auto_now=True), preserve_default=False, ), Change this one operation into 3 … Read more

Creating Partial Indexes with Django 1.7

Django 2.2 and later As of version 2.2 Django supports declarative partial unique indexes on databases that support them (PostgreSQL and SQLite). So you could do something like: from django.db.models import Model, Q, UniqueConstraint class Post(Model): … class Meta: constraints = [ UniqueConstraint( fields=[“title”, “blog”, “category”], name=”idx1″, condition=Q(category__isnull=False)), UniqueConstraint( fields=[“title”, “blog”], name=”idx2″, condition=Q(category__isnull=True)), ] Django … Read more

Django migration with uuid field generates duplicated values

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 … Read more