Skip to content

Commit

Permalink
feat(signals): duplicate objects with field constraints
Browse files Browse the repository at this point in the history
Add pre_duplicate signal to deal with fields of entity
object instances which won't allow object duplication
(e.g. fields with unique constraints).
  • Loading branch information
koeaw committed Jul 3, 2024
1 parent d8152b8 commit 644659a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion apis_ontology/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from django.utils.translation import gettext_lazy as _
from multiselectfield import MultiSelectField

from .signals import update_duplicates # noqa
from .signals import prepare_for_duplication, update_duplicates # noqa


logger = logging.getLogger(__name__)
Expand Down
24 changes: 23 additions & 1 deletion apis_ontology/signals.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
import logging

from apis_core.apis_metainfo.models import RootObject
from apis_core.apis_metainfo.signals import post_duplicate
from apis_core.apis_metainfo.signals import post_duplicate, pre_duplicate
from django.dispatch import receiver


logger = logging.getLogger(__name__)


@receiver(pre_duplicate)
def prepare_for_duplication(sender, instance, **kwargs):
"""
Prepare instances of entity classes before duplicating them
by removing or updating fields which won't pass validation.
Helps to e.g. circumvent IntegrityErrors caused by unique constraints.
:param sender: the model class
:param instance: the original object
"""
if isinstance(instance, RootObject):
available_fields = [f.name for f in instance._meta.fields]

update_fields = {
"siglum": None,
}

for f, v in update_fields.items():
if f in available_fields:
setattr(instance, f, v)


@receiver(post_duplicate)
def update_duplicates(sender, instance, duplicate, **kwargs):
"""
Expand Down

0 comments on commit 644659a

Please sign in to comment.