+def _tags_updated_handler(sender, affected_tags, **kwargs):
+ # reset tag global counter
+ Tag.objects.filter(pk__in=[tag.pk for tag in affected_tags]).update(book_count=None)
+
+ # if book tags changed, reset book tag counter
+ if isinstance(sender, Book) and \
+ Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
+ exclude(category__in=('book', 'theme', 'set')).count():
+ sender.reset_tag_counter()
+ # if fragment theme changed, reset book theme counter
+ elif isinstance(sender, Fragment) and \
+ Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
+ filter(category='theme').count():
+ sender.book.reset_theme_counter()
+tags_updated.connect(_tags_updated_handler)
+