Coverage for apis_core/relations/signals.py: 52%
29 statements
« prev ^ index » next coverage.py v7.6.8, created at 2024-12-20 09:24 +0000
« prev ^ index » next coverage.py v7.6.8, created at 2024-12-20 09:24 +0000
1import logging
3from django.contrib.contenttypes.models import ContentType
4from django.dispatch import receiver
6from apis_core.generic.signals import post_duplicate, post_merge_with
7from apis_core.relations.models import Relation
9logger = logging.getLogger(__name__)
12@receiver(post_duplicate)
13def copy_relations(sender, instance, duplicate, **kwargs):
14 logger.info(f"Copying relations from {instance!r} to {duplicate!r}")
15 content_type = ContentType.objects.get_for_model(instance)
16 subj_rels = Relation.objects.filter(
17 subj_content_type=content_type, subj_object_id=instance.id
18 ).select_subclasses()
19 obj_rels = Relation.objects.filter(
20 obj_content_type=content_type, obj_object_id=instance.id
21 ).select_subclasses()
22 for rel in subj_rels:
23 rel.pk = None
24 rel.id = None
25 rel.subj_object_id = duplicate.id
26 rel.save()
27 for rel in obj_rels:
28 rel.pk = None
29 rel.id = None
30 rel.obj_object_id = duplicate.id
31 rel.save()
34@receiver(post_merge_with)
35def merge_relations(sender, instance, entities, **kwargs):
36 for ent in entities:
37 logger.info(f"Merging relations from {ent!r} into {instance!r}")
38 content_type = ContentType.objects.get_for_model(ent)
39 Relation.objects.filter(
40 subj_content_type=content_type, subj_object_id=ent.id
41 ).update(subj_object_id=instance.id)
42 Relation.objects.filter(
43 obj_content_type=content_type, obj_object_id=ent.id
44 ).update(obj_object_id=instance.id)