Skip to content

Instantly share code, notes, and snippets.

@DArmstrong87
Last active March 20, 2024 14:45
Show Gist options
  • Save DArmstrong87/9b65c3b89c263f68f673271e2970026d to your computer and use it in GitHub Desktop.
Save DArmstrong87/9b65c3b89c263f68f673271e2970026d to your computer and use it in GitHub Desktop.
Django migrations: Run Python function that takes optional parameter when reversing migration
from django.db import migrations
from myapp.models import MyModel
def convert_mymodel_status(apps, schema_editor, reverse: bool | None = False):
"""
Convert "OLD STATUS" status to "NEW STATUS"
Or reverses these changes
"""
status = "NEW STATUS" if reverse else "OLD STATUS"
updated_status = "OLD STATUS" if reverse else "NEW STATUS"
MyModel.objects.filter(status=status).update(status=updated_status)
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.RunPython(
code=convert_mymodel_status,
reverse_code=lambda apps, schema_editor: convert_mymodel_status(
apps, schema_editor, True
),
)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment