from django.db import migrations, models from django.utils import timezone def backfill_sent_to_department(apps, schema_editor): Observation = apps.get_model("observations", "Observation") Observation.objects.filter( assigned_department__isnull=False ).update(sent_to_department=True) Observation.objects.filter( sent_to_department=True, sent_to_department_at__isnull=True, forwarded_to_dept_at__isnull=False, ).update(sent_to_department_at=models.F("forwarded_to_dept_at")) Observation.objects.filter( sent_to_department=True, sent_to_department_at__isnull=True ).update(sent_to_department_at=timezone.now()) def reverse_backfill(apps, schema_editor): Observation = apps.get_model("observations", "Observation") Observation.objects.all().update( sent_to_department=False, sent_to_department_at=None ) class Migration(migrations.Migration): dependencies = [ ("observations", "0004_add_sent_to_department_fields"), ] operations = [ migrations.RunPython(backfill_sent_to_department, reverse_backfill), ]