1👍
-
Instead of a list of ids pass a queryset to
object_pk__in
condition. Django is smart enough to translate this into SQL subquery so all expenses will be handled by SQL server which is smart too 🙂 -
Use queryset’s
in_bulk()
method to get an easy accessible dict of Books.
So code will look something like this:
# just queryset instead of tuple of ids
books = Books.objects.filter(language=language).values_list('id', flat=True)
rating = list(HitCount.objects.filter(content_type=content_type,
object_pk__in=books)
.values_list('object_pk', 'hits')
.order_by('-hits')[:15])
book_ids = [r[0] for r in rating]
# dict of Books with book.pk as a key
books_d = Books.objects.select_related('manga').in_bulk(book_ids)
# list of tuples (book, hits) ordered by -hits
best_of_all_time = [books_d[pk], hits for pk, hits in rating]
Source:stackexchange.com