Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>threads = Thread.objects.filter( Q(message_set__from_user=u) | Q(message_set__to_user=u) ).order_by('id') messages = Message.objects.filter( Q(thread__in=threads) &amp; Q(Q(thread__from_user=u) | Q(thread_to_user=u)) ).order_by('thread__id', '-when').select_related('from_user', 'to_user') from itertools import groupby t_index = 0 for thread_messages in groupby(messages, lambda x: x.thread_id): if threads[t_index].id is thread_messages[0].thread_id: threads[t_index].messages = thread_messages t_index += 1 </code></pre> <p>That might look a bit complex or scary but it <em>should</em> do what you are after. Essentially it queries all your threads first so we can find out what threads we've messaged about. Then it finds all the related messages to those threads.</p> <p>Both of the queries are ordered by the same field so that in the lower part of the code we can iterate through the list only once, instead of needing a nested for loop to find each thread with the correct id. They are also both filtered by the same query (regarding thread objects at least) to ensure we are getting back only the relevant results to this query.</p> <p>Lastly, the messages that we received back are grouped together and attached to each thread; they will show up in descending order for each thread.</p> <p>Right at the end, you may also want to re-sort your threads to show the latest ones first, easy to do assuming a 'when' field on the Thread model:</p> <p>threads = sorted(threads, key=lambda x: x.when, reverse=True)</p> <p>By using the aforementioned method, you will have to do 2 queries every time, regardless, first the threads, then the messages. But it will never go above this (watch out for joins on a select_related though or recursive queries on related objects).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload