- related = Book.tagged.related_to(book,
- Book.objects.exclude(common_slug=book.common_slug)
- ).exclude(ancestor=book)[:limit-random]
- random_excluded = [b.pk for b in related] + [book.pk]
+ max_books = limit - random
+ is_picture = isinstance(instance, Picture)
+
+ pics_qs = Picture.objects.all()
+ if is_picture:
+ pics_qs = pics_qs.exclude(pk=instance.pk)
+ pics = Picture.tagged.related_to(instance, pics_qs)
+ if pics.exists():
+ # Reserve one spot for an image.
+ max_books -= 1
+
+ books_qs = Book.objects.all()
+ if not is_picture:
+ books_qs = books_qs.exclude(common_slug=instance.common_slug).exclude(ancestor=instance)
+ books = Book.tagged.related_to(instance, books_qs)[:max_books]
+
+ pics = pics[:1 + max_books - books.count()]
+
+ random_excluded_books = [b.pk for b in books]
+ random_excluded_pics = [p.pk for p in pics]
+ (random_excluded_pics if is_picture else random_excluded_books).append(instance.pk)
+