diff options
Diffstat (limited to 'ishtar_common/model_merging.py')
| -rw-r--r-- | ishtar_common/model_merging.py | 29 | 
1 files changed, 23 insertions, 6 deletions
| diff --git a/ishtar_common/model_merging.py b/ishtar_common/model_merging.py index c577a8cf1..a390f233c 100644 --- a/ishtar_common/model_merging.py +++ b/ishtar_common/model_merging.py @@ -1,11 +1,25 @@  # from https://djangosnippets.org/snippets/2283/ +from django.apps import apps  from django.db import transaction -from django.db.models import get_models, Model -from django.contrib.contenttypes.generic import GenericForeignKey +from django.db.models import Model +from django.contrib.contenttypes.fields import GenericForeignKey +from django.core.exceptions import ObjectDoesNotExist +from ishtar_common.utils import get_all_related_many_to_many_objects, \ +    get_all_related_objects -@transaction.commit_on_success + +def get_models(): +    _apps = apps.app_configs.items() +    models = [] +    for app_name, app_config in _apps: +        models += [apps.get_model(app_name, m) +                   for m in apps.get_app_config(app_name).models] +    return models + + +@transaction.atomic  def merge_model_objects(primary_object, alias_objects=[], keep_old=False):      """      Use this function to merge model objects (i.e. Users, Organizations, Polls, @@ -58,12 +72,15 @@ def merge_model_objects(primary_object, alias_objects=[], keep_old=False):      for alias_object in alias_objects:          # Migrate all foreign key references from alias object to primary          # object. -        for related_object in alias_object._meta.get_all_related_objects(): +        for related_object in get_all_related_objects(alias_object):              # The variable name on the alias_object model.              alias_varname = related_object.get_accessor_name()              # The variable name on the related model.              obj_varname = related_object.field.name -            related_objects = getattr(alias_object, alias_varname) +            try: +                related_objects = getattr(alias_object, alias_varname) +            except ObjectDoesNotExist: +                continue              for obj in related_objects.all():                  setattr(obj, obj_varname, primary_object)                  obj.save() @@ -71,7 +88,7 @@ def merge_model_objects(primary_object, alias_objects=[], keep_old=False):          # Migrate all many to many references from alias object to primary          # object.          related_many_objects = \ -            alias_object._meta.get_all_related_many_to_many_objects() +            get_all_related_many_to_many_objects(alias_object)          related_many_object_names = set()          for related_many_object in related_many_objects:              alias_varname = related_many_object.get_accessor_name() | 
