Skip to content

Commit

Permalink
feat(relations): implement duplicate and merge signal receivers
Browse files Browse the repository at this point in the history
Closes: #1251
  • Loading branch information
b1rger committed Oct 21, 2024
1 parent 29b8038 commit 1940098
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions apis_core/relations/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class RelationsNgConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "apis_core.relations"

def ready(self):
from . import signals # noqa: F401
36 changes: 36 additions & 0 deletions apis_core/relations/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import logging

from django.dispatch import receiver
from django.contrib.contenttypes.models import ContentType

from apis_core.apis_entities.signals import post_merge_with
from apis_core.apis_metainfo.signals import post_duplicate

from apis_core.relations.models import Relation

logger = logging.getLogger(__name__)


@receiver(post_duplicate)
def copy_relations(sender, instance, duplicate, **kwargs):
logger.info(f"Copying relations from {instance!r} to {duplicate!r}")
content_type = ContentType.objects.get_for_model(instance)
subj_rels = Relation.objects.filter(subj_content_type=content_type, subj_object_id=instance.id).select_subclasses()
obj_rels = Relation.objects.filter(obj_content_type=content_type, obj_object_id=instance.id).select_subclasses()
for rel in subj_rels:
rel.pk = None
rel.subj_object_id = duplicate.id
rel.save()
for rel in obj_rels:
rel.pk = None
rel.obj_object_id = duplicate.id
rel.save()


@receiver(post_merge_with)
def merge_relations(sender, instance, entities, **kwargs):
for ent in entities:
logger.info(f"Merging relations from {ent!r} into {instance!r}")
content_type = ContentType.objects.get_for_model(ent)
Relation.objects.filter(subj_content_type=content_type, subj_object_id=ent.id).update(subj_object_id=instance.id)
Relation.objects.filter(obj_content_type=content_type, obj_object_id=ent.id).update(obj_object_id=instance.id)

0 comments on commit 1940098

Please sign in to comment.