import json

from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand

from api_manager.models import GroupProfile, Organization

class Command(BaseCommand):
    """
    Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
    """

    def handle(self, *args, **options):

        org_groups = GroupProfile.objects.filter(group_type='organization')

        for org in org_groups:
            data = json.loads(org.data)
            migrated_org = Organization.objects.create(
                name=data['name'],
                display_name=data['display_name'],
                contact_name=data['contact_name'],
                contact_email=data['contact_email'],
                contact_phone=data['contact_phone']
            )
            group = Group.objects.get(groupprofile=org.id)
            users = group.user_set.all()
            for user in users:
                migrated_org.users.add(user)
            linked_groups = group.grouprelationship.get_linked_group_relationships()
            for linked_group in linked_groups:
                if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
                    actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
                    migrated_org.groups.add(actual_group)

@@ -527,16 +527,470 @@
 g.data)%0A
+%0A            name = org.name%0A            display_name = data.get('display_name', name)%0A            contact_name = data.get('contact_name', None)%0A            contact_email = data.get('email', None)%0A            if contact_email is None:%0A                contact_email = data.get('contact_email', None)%0A            contact_phone = data.get('phone', None)%0A            if contact_phone is None:%0A                contact_phone = data.get('contact_phone', None)%0A%0A
         
@@ -1062,20 +1062,12 @@
 ame=
-data%5B'
 name
-'%5D
 ,%0A  
@@ -1093,22 +1093,16 @@
 ay_name=
-data%5B'
 display_
@@ -1101,26 +1101,24 @@
 display_name
-'%5D
 ,%0A          
@@ -1136,22 +1136,16 @@
 ct_name=
-data%5B'
 contact_
@@ -1148,18 +1148,16 @@
 act_name
-'%5D
 ,%0A      
@@ -1180,22 +1180,16 @@
 t_email=
-data%5B'
 contact_
@@ -1193,18 +1193,16 @@
 ct_email
-'%5D
 ,%0A      
@@ -1229,14 +1229,8 @@
 one=
-data%5B'
 cont
@@ -1242,10 +1242,8 @@
 hone
-'%5D
 %0A   

Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present