@@ -10,13 +10,17 @@ def migrate_channels_to_notificationchannel(apps, schema_editor):
1010 NotificationChannel = apps .get_model ("generic_notifications" , "NotificationChannel" )
1111
1212 for notification in Notification .objects .all ():
13+ # Access the channels_old JSONField (renamed to avoid conflict)
14+ channels_data = notification .channels_old if hasattr (notification , "channels_old" ) else []
15+
1316 # Create NotificationChannel entries for each channel
14- for channel in notification . channels :
17+ for channel in channels_data :
1518 delivery , created = NotificationChannel .objects .get_or_create (
1619 notification = notification ,
1720 channel = channel ,
1821 )
1922
23+ # If this is the email channel and email_sent_at is set, update sent_at
2024 if notification .email_sent_at :
2125 delivery .sent_at = notification .email_sent_at
2226 delivery .save ()
@@ -29,12 +33,12 @@ def reverse_migrate_channels(apps, schema_editor):
2933
3034 for notification in Notification .objects .all ():
3135 # Rebuild channels list from NotificationChannel entries
32- channels = list (notification . channels .values_list ("channel" , flat = True ))
33- notification .channels = channels
36+ channels = list (NotificationChannel . objects . filter ( notification = notification ) .values_list ("channel" , flat = True ))
37+ notification .channels_old = channels
3438
3539 # Restore email_sent_at from email NotificationChannel
3640 try :
37- email_delivery = notification . channels .get (channel = "email" )
41+ email_delivery = NotificationChannel . objects .get (notification = notification , channel = "email" )
3842 if email_delivery .sent_at :
3943 notification .email_sent_at = email_delivery .sent_at
4044 except NotificationChannel .DoesNotExist :
@@ -49,6 +53,13 @@ class Migration(migrations.Migration):
4953 ]
5054
5155 operations = [
56+ # First, rename the channels field to avoid naming conflict with the related_name
57+ migrations .RenameField (
58+ model_name = "notification" ,
59+ old_name = "channels" ,
60+ new_name = "channels_old" ,
61+ ),
62+ # Create the new NotificationChannel model
5263 migrations .CreateModel (
5364 name = "NotificationChannel" ,
5465 fields = [
@@ -72,8 +83,15 @@ class Migration(migrations.Migration):
7283 "unique_together" : {("notification" , "channel" )},
7384 },
7485 ),
86+ # Migrate the data
7587 migrations .RunPython (
7688 migrate_channels_to_notificationchannel ,
7789 reverse_migrate_channels ,
7890 ),
91+ # Rename back to channels for migration 3 to handle removal
92+ migrations .RenameField (
93+ model_name = "notification" ,
94+ old_name = "channels_old" ,
95+ new_name = "channels" ,
96+ ),
7997 ]
0 commit comments