diff --git a/src/viralhostrange/viralhostrangedb/forms.py b/src/viralhostrange/viralhostrangedb/forms.py index 26cfb701170e086b19400d5c9d588ba582ededd9..e71b26bce87333ab6be0e1fc6b38eeb1221a320a 100644 --- a/src/viralhostrange/viralhostrangedb/forms.py +++ b/src/viralhostrange/viralhostrangedb/forms.py @@ -448,12 +448,6 @@ class AutoMergeSplitUpdateFormSet(forms.BaseModelFormSet): self.has_her_identifier = False def save(self, commit=True): - # objects = super().save(commit=False) - # self.save_m2m() - # for obj, reason in self.changed_objects: - # obj.save() - # - # def saveXXX(self, commit=True): assert (self.__data_source is not None) assert commit, "It has to be actually saved in DB" objects = super().save(commit=False) @@ -469,19 +463,25 @@ class AutoMergeSplitUpdateFormSet(forms.BaseModelFormSet): .filter(~Q(pk=obj.pk)) if self.has_her_identifier: alter_egos = alter_egos.filter(her_identifier=obj.her_identifier) + # alter_ego is the object to which we have to rename the obj alter_ego = alter_egos.first() + # If there is no alter_ego we may have to build one new if alter_ego is None: + # If we can get the is_ncbi_identifier_value elsewhere then we re-use it if 'identifier' in reason: identifier_alter_ego = obj.__class__.objects.filter(identifier=obj.identifier).first() if identifier_alter_ego is None: obj.is_ncbi_identifier_value = None else: obj.is_ncbi_identifier_value = identifier_alter_ego.is_ncbi_identifier_value + # If the object is not used by someone else then we just change it if obj.data_source.count() == 1: obj.save() continue + # obj is used, we clone it obj.pk = None obj.save() + # And use this copy as its alter_ego alter_ego = obj # remove the old instance from the current data_source @@ -490,7 +490,7 @@ class AutoMergeSplitUpdateFormSet(forms.BaseModelFormSet): # in any case, replace the instance that was about to be returned by the alter ego/newly created one indexed_objects[old_o.pk] = alter_ego - # obj is now an other db instance, while old_o is still pointing to the original db instance + # obj is now a new db instance, while old_o is still pointing to the original db instance # add the new instance to the data source alter_ego.data_source.add(self.__data_source)