2
Prefetch the related data manually (from N+1 -> 3 queries).
thread_ids = [message.thread_id for message in message_list]
user_ids = [message.user_id for message in message_list]
users = {u.id: u for u in User.objects.filter(id__in=user_ids)}
threads = {t.id for t in Thread.objects.filter(id__in=thread_ids)}
Then you can either pass the users and threads dicts to your template, or loop over messages and attach them manually
for message in message_list:
message.thread = threads.get(message.thread_id)
message.user = users.get(message.user_id)
0
Well you should have it in one DB or use caching, but there is no way you can reduce the query.
I would probably go with caching. You could also somehow prefetch the user in init but I am not sure if that is the good idea. This is simply bad design.
- [Answered ]-Migrate Database of Django 1.4 application to Django 1.8 version
- [Answered ]-Making two player chess app with Django– need player's board to update when opponent makes a move
Source:stackexchange.com