Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you prefer single query and are using <code>MySQL</code>, check <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/" rel="nofollow">the excellent link</a> provided by @Crazyshezy in his comment.<br> For <code>PostgreSQL</code> backends, a possible query is (assuming there are non-nullable <code>FK</code> relationships from <code>Book</code> to <code>Author</code> and from <code>Author</code> to <code>Category</code>):</p> <pre><code>SELECT * FROM ( SELECT book_table.*, row_number() OVER (PARTITION BY category_id ORDER BY RANDOM()) AS rn FROM book_table INNER JOIN author_table ON book_table.author_id = author_table.id ) AS sq WHERE rn &lt;= 5 </code></pre> <p>You could then wrap it inside a <code>RawQuerySet</code> to get <code>Book</code> instances</p> <pre><code>from collections import defaultdict qs = Book.objects.raw("""The above sql suited for your tables...""") collection = defaultdict(list) for obj in qs: collection[obj.category_id].append(obj) categories_w_rand_books = [] for category in c: categories_w_rand_books.append((category, collection[category.id])) </code></pre> <p>You may not want to run this query for each request directly w/o some caching.</p> <p>Furthermore, your code generates at most 50*5=250 <code>Book</code>s, randomly, I just wonder why because it seems too many for a single page. Are items displayed as tabs or something else? Perhaps you could reduce the counts of SQLs by doing Ajax, or simplify the requirement?</p> <p><em>Update</em></p> <p>To use <code>book.author</code> w/o triggering more than another query, try <code>prefetch_related_objects</code></p> <pre><code>from django.db.models.query import prefetch_related_objects qs = list(qs) # have to evaluate at first prefetch_related_objects(qs, ['author']) # now instances inside qs already contain cached author instances, and qs[0].author # will not trigger an extra query </code></pre> <p>The above code prefetches authors in batch and fills them into the <code>qs</code>. This just adds another query. </p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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