- books = models.Book.tagged.with_all(tags).order_by()
- l_tags = [models.Tag.objects.get(slug='l-' + book.slug) for book in books]
- book_keys = [book.pk for book in books]
- # newtagging goes crazy if we just try:
- #related_tags = models.Tag.objects.usage_for_queryset(books, counts=True,
- # extra={'where': ["catalogue_tag.category NOT IN ('set', 'book', 'theme')"]})
- if book_keys:
- related_tags = models.Book.tags.usage(counts=True,
- filters={'pk__in': book_keys},
- extra={'where': ["catalogue_tag.category NOT IN ('set', 'book', 'theme')"]})
- categories = split_tags(related_tags)
-
- fragment_keys = [fragment.pk for fragment in models.Fragment.tagged.with_any(l_tags)]
- if fragment_keys:
- categories['theme'] = models.Fragment.tags.usage(counts=True,
- filters={'pk__in': fragment_keys},
- extra={'where': ["catalogue_tag.category = 'theme'"]})
-
- books = books.exclude(parent__in=book_keys)
- objects = books
+ # get relevant books and their tags
+ objects = models.Book.tagged.with_all(tags).order_by()
+ if not shelf_is_set:
+ # eliminate descendants
+ l_tags = models.Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
+ descendants_keys = [book.pk for book in models.Book.tagged.with_any(l_tags)]
+ if descendants_keys:
+ objects = objects.exclude(pk__in=descendants_keys)
+
+ # get related tags from `tag_counter` and `theme_counter`
+ related_counts = {}
+ tags_pks = [tag.pk for tag in tags]
+ for book in objects:
+ for tag_pk, value in itertools.chain(book.tag_counter.iteritems(), book.theme_counter.iteritems()):
+ if tag_pk in tags_pks:
+ continue
+ related_counts[tag_pk] = related_counts.get(tag_pk, 0) + value
+ related_tags = models.Tag.objects.filter(pk__in=related_counts.keys())
+ related_tags = [tag for tag in related_tags if tag not in tags]
+ for tag in related_tags:
+ tag.count = related_counts[tag.pk]
+
+ categories = split_tags(related_tags)
+ del related_tags