|
| 1 | +from django.db import migrations |
| 2 | + |
| 3 | + |
| 4 | +def switch_to_new_token_model(apps, _): |
| 5 | + OldTokenAuth = apps.get_model("token", "OldTokenAuth") |
| 6 | + TokenAuth = apps.get_model("token", "TokenAuth") |
| 7 | + |
| 8 | + for old_token in OldTokenAuth.objects.all(): |
| 9 | + token, created = TokenAuth.objects.get_or_create( |
| 10 | + token=old_token.token, |
| 11 | + defaults={ |
| 12 | + "contact_person": old_token.contact_person, |
| 13 | + "email": old_token.email, |
| 14 | + "organization": old_token.organization, |
| 15 | + "last_modified": old_token.last_modified, |
| 16 | + "created": old_token.created, |
| 17 | + "application": old_token.application, |
| 18 | + "administration": old_token.administration, |
| 19 | + }, |
| 20 | + ) |
| 21 | + |
| 22 | + # add fk relations to new model |
| 23 | + if created: |
| 24 | + old_token.permissions.all().update(new_token_auth=token) |
| 25 | + |
| 26 | + |
| 27 | +def switch_to_old_token_model(apps, _): |
| 28 | + OldTokenAuth = apps.get_model("token", "OldTokenAuth") |
| 29 | + TokenAuth = apps.get_model("token", "TokenAuth") |
| 30 | + |
| 31 | + # copy tokens to old model |
| 32 | + for token in TokenAuth.objects.all(): |
| 33 | + old_token, created = OldTokenAuth.objects.get_or_create( |
| 34 | + token=token.token, |
| 35 | + defaults={ |
| 36 | + "contact_person": token.contact_person, |
| 37 | + "email": token.email, |
| 38 | + "organization": token.organization, |
| 39 | + "last_modified": token.last_modified, |
| 40 | + "created": token.created, |
| 41 | + "application": token.application, |
| 42 | + "administration": token.administration, |
| 43 | + }, |
| 44 | + ) |
| 45 | + |
| 46 | + # add fk relations to old model |
| 47 | + if created: |
| 48 | + token.permissions.all().update(old_token_auth=old_token) |
| 49 | + |
| 50 | + |
| 51 | +class Migration(migrations.Migration): |
| 52 | + dependencies = [ |
| 53 | + ("token", "0012_tokenauth_permission_token_auth"), |
| 54 | + ] |
| 55 | + |
| 56 | + operations = [ |
| 57 | + migrations.RunPython(switch_to_new_token_model, switch_to_old_token_model), |
| 58 | + ] |
0 commit comments