Created
January 8, 2017 03:22
-
-
Save grahamu/f7191137a2b75d109235640f0ecee193 to your computer and use it in GitHub Desktop.
clientorg_migration.py
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
# coding: utf-8 | |
def command(): | |
""" | |
Management command creates ClientOrgs and ClientMemberships | |
from existing Users and their Assigned*Account attributes. | |
""" | |
client_orgs = [] | |
members = [] | |
save = False | |
for user in User.objects.all(): | |
if not user.email: | |
print('No email found for user {}'.format(user)) | |
continue | |
is_admin = False # how can we determine if user is an admin? | |
domain = get_domain(user.email) | |
org = next(iter(ClientOrg.objects.filter(name=domain)), None) | |
if not org: | |
# Get Assigned* account info | |
has_automation = hasattr(user, 'assignedautomationaccount') | |
... | |
org = ClientOrg.objects.create( | |
name=domain, | |
# set access based on user Assigned accounts | |
has_automation=has_automation, | |
... | |
) if save else domain | |
client_orgs.append(org) | |
print('New ClientOrg: {}'.format(domain)) | |
if ClientMembership.objects.filter(user=user, client_org=org): | |
print('Skipping user {} already in organization {}'.format(user, org)) | |
continue | |
membership = ClientMembership.objects.create( | |
# set unique_together=['client_org', 'user'] in model! | |
client_org=org, | |
user=user, | |
is_admin=is_admin | |
) if save else user | |
members.append(membership) | |
print('{} ClientOrgs'.format(len(client_orgs))) | |
print('{} ClientMemberships for {} users'.format(len(members), User.count())) | |
def get_domain(addr): | |
address_parts = addr.split('@') | |
if len(address_parts) > 1: | |
domain = address_parts[1] | |
else: | |
domain = '' | |
return domain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment