Last active
March 20, 2024 14:45
-
-
Save DArmstrong87/9b65c3b89c263f68f673271e2970026d to your computer and use it in GitHub Desktop.
Django migrations: Run Python function that takes optional parameter when reversing migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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