|
| 1 | +# Generated by Django 5.1.1 on 2024-12-01 17:59 |
| 2 | + |
| 3 | +from django.db import migrations, models |
| 4 | +import json |
| 5 | + |
| 6 | +def forwards_func(apps, schema_editor): |
| 7 | + Grant = apps.get_model('grants', 'Grant') |
| 8 | + for grant in Grant.objects.all(): |
| 9 | + old_value = grant.grant_type |
| 10 | + # Convert the old string value into a list |
| 11 | + grant.grant_type_json = [old_value] if old_value else [] |
| 12 | + grant.save(update_fields=['grant_type_json']) |
| 13 | + |
| 14 | +def reverse_func(apps, schema_editor): |
| 15 | + Grant = apps.get_model('grants', 'Grant') |
| 16 | + for grant in Grant.objects.all(): |
| 17 | + value_list = grant.grant_type |
| 18 | + # Convert the list back to a single string |
| 19 | + if value_list: |
| 20 | + grant.grant_type = value_list[0] |
| 21 | + else: |
| 22 | + grant.grant_type = '' |
| 23 | + grant.save(update_fields=['grant_type']) |
| 24 | + |
| 25 | +class Migration(migrations.Migration): |
| 26 | + dependencies = [ |
| 27 | + ("grants", "0022_grant_departure_city_grant_nationality_and_more"), |
| 28 | + ] |
| 29 | + |
| 30 | + operations = [ |
| 31 | + # Step 1: Add a temporary JSONField |
| 32 | + migrations.AddField( |
| 33 | + model_name='grant', |
| 34 | + name='grant_type_json', |
| 35 | + field=models.JSONField(default=list, verbose_name="grant type"), |
| 36 | + ), |
| 37 | + # Step 2: Backfill data into the temporary field |
| 38 | + migrations.RunPython(forwards_func, reverse_func), |
| 39 | + # Step 3: Remove the old field |
| 40 | + migrations.RemoveField( |
| 41 | + model_name='grant', |
| 42 | + name='grant_type', |
| 43 | + ), |
| 44 | + # Step 4: Rename the temporary field to grant_type |
| 45 | + migrations.RenameField( |
| 46 | + model_name='grant', |
| 47 | + old_name='grant_type_json', |
| 48 | + new_name='grant_type', |
| 49 | + ), |
| 50 | + ] |
0 commit comments