- for book in models.Book.objects.all().order_by('parent_number'):
- books_by_parent.setdefault(book.parent, []).append(book)
+ books = models.Book.objects.all().order_by('parent_number', 'title').only('title', 'parent', 'slug')
+ if filter:
+ books = books.filter(filter)
+ book_ids = set((book.pk for book in books))
+ for book in books:
+ parent = book.parent_id
+ if parent not in book_ids:
+ parent = None
+ books_by_parent.setdefault(parent, []).append(book)
+ else:
+ for book in books:
+ books_by_parent.setdefault(book.parent_id, []).append(book)