Created
July 10, 2019 15:07
-
-
Save pirate/3055ccf8663cf5d62634888201f5142a to your computer and use it in GitHub Desktop.
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
def get_master_from_obj_id(org, obj_type: str, obj_id: str): | |
from sync.models import Master, Version | |
try: | |
version = Version.objects.filter( | |
source__organization_id=org.id, | |
obj_type=obj_type, | |
obj_id=obj_id, | |
mapping__isnull=False, | |
mapping__master_id__isnull=False, | |
).last() | |
if not version.mapping.master: | |
raise Master.DoesNotExist | |
return version.mapping.master | |
except (Version.DoesNotExist, Master.DoesNotExist): | |
print("Tried to translate an ID for an object that hasn't been pulled yet") | |
def translate_field_values(obj: dict, fields: FieldsType) -> FieldsType: | |
from core.models import Organization | |
translated_obj = {} | |
org = Organization.objects.get(id=obj['meta']['source_organization_id']) | |
for key, field in fields.items(): | |
if field['sync'] == 'off': | |
continue | |
if field['sync'] == 'pk': | |
value = get_master_from_obj_id(org, obj['meta']['obj_type'], obj[key]) | |
elif field['sync'] == 'verbatim': | |
value = obj[key] | |
elif field['sync'] == 'master': | |
structure = 'plain' | |
obj_type = field['type'] | |
if obj_type.startswith('[') and obj_type.endswith(']'): | |
obj_type = obj_type[1:-1] | |
structure = 'list' | |
assert field['structure'] == structure | |
elif obj_type.startswith('{') and obj_type.endswith('}'): | |
obj_type = obj_type[1:-1] | |
structure = 'dict' | |
assert field['structure'] == structure | |
else: | |
assert field.get('structure') is None | |
if structure == 'plain': | |
value = get_master_from_obj_id(org, obj_type, obj[key]) | |
elif structure == 'list': | |
value = [ | |
get_master_from_obj_id(org, obj_type, id) | |
for id in obj[key] | |
] | |
elif structure == 'dict': | |
# raise NotImplementedError() | |
# value = { | |
# get_master_from_obj_id(org, obj_type, subkey) | |
# for subkey, val in obj[key] | |
# } | |
value = obj[key] | |
else: | |
raise NotImplementedError(f'{field["sync"]} sync type not implemented yet') | |
translated_obj[key] = { | |
**field, | |
'value': value, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment