X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/9c5d9a4e77a10b4e60d89d3890e49002bd7f3993..8e2e65fd5f86516e7d15df0c1106a0b861bfb011:/apps/newtagging/models.py diff --git a/apps/newtagging/models.py b/apps/newtagging/models.py index 1c35254bb..ea2a41f8e 100644 --- a/apps/newtagging/models.py +++ b/apps/newtagging/models.py @@ -15,6 +15,7 @@ from django.db import connection, models from django.utils.translation import ugettext_lazy as _ from django.db.models.base import ModelBase from django.core.exceptions import ObjectDoesNotExist +from django.dispatch import Signal qn = connection.ops.quote_name @@ -24,6 +25,8 @@ except ImportError: parse_lookup = None +tags_updated = Signal(providing_args=["affected_tags"]) + def get_queryset_and_model(queryset_or_model): """ Given a ``QuerySet`` or a ``Model``, returns a two-tuple of @@ -45,6 +48,16 @@ class TagManager(models.Manager): def __init__(self, intermediary_table_model): super(TagManager, self).__init__() self.intermediary_table_model = intermediary_table_model + models.signals.pre_delete.connect(self.target_deleted) + + def target_deleted(self, instance, **kwargs): + """ clear tag relations before deleting an object """ + try: + int(instance.pk) + except ValueError: + return + + self.update_tags(instance, []) def update_tags(self, obj, tags): """ @@ -63,10 +76,14 @@ class TagManager(models.Manager): object_id=obj.pk, tag__in=tags_for_removal).delete() # Add new tags - for tag in updated_tags: + tags_to_add = [tag for tag in updated_tags + if tag not in current_tags] + for tag in tags_to_add: if tag not in current_tags: self.intermediary_table_model._default_manager.create(tag=tag, content_object=obj) + tags_updated.send(sender=obj, affected_tags=tags_to_add + tags_for_removal) + def remove_tag(self, obj, tag): """ Remove tag from an object.