I've been trying to optimize this Django query set search the last two days and have been unable to speed it up. My backend is MYSQL.
There are three tables: Book, Bookstore and Category. Book has 1 million observations, Bookstore has 500 observations and category has 10k observations
table = Book.objects.filter(Category=pk, bookstore__in=bookstore_objects).order_by('title').prefetch_related(Prefetch('bookstore', to_attr='bookstore_list'))[:50]
The first time this query is run-in the shell it takes 20+ seconds and subsequently it takes about 3-5 seconds. Please help me speed up this query. I cannot understand why it's so slow.