Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9065679
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:33:57+00:00 2026-06-16T16:33:57+00:00

This code is currently executing about 50 SQL queries: c = Category.objects.all() categories_w_rand_books =

  • 0

This code is currently executing about 50 SQL queries:

c = Category.objects.all()

categories_w_rand_books = []

for category in c:
    r = Book.objects.filter(author__category=category).order_by('?')[:5]

    categories_w_rand_books.append((category, r))

I need to cut down the number of used queries to the minimum to speed up things and do not cause server load.

Basically, I have three models: Category, Author, Book. The Author belong to the Category (not books) and I need to get a list of all categories with 5 random books under each one.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T16:33:58+00:00Added an answer on June 16, 2026 at 4:33 pm

    If you prefer single query and are using MySQL, check the excellent link provided by @Crazyshezy in his comment.
    For PostgreSQL backends, a possible query is (assuming there are non-nullable FK relationships from Book to Author and from Author to Category):

    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 <= 5 
    

    You could then wrap it inside a RawQuerySet to get Book instances

    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]))
    

    You may not want to run this query for each request directly w/o some caching.

    Furthermore, your code generates at most 50*5=250 Books, 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?

    Update

    To use book.author w/o triggering more than another query, try prefetch_related_objects

    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
    

    The above code prefetches authors in batch and fills them into the qs. This just adds another query.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

From what I've read about Tasks, the following code should cancel the currently executing
Currently this code generates a colored hyperlink to an ad listing on my site.
This is my code currently: $(function() { $('#header_left').click(function(){ $('#header_left_info').fadeOut('fast'); $('#header_left').fadeOut('fast'); $('#header_left_back').delay(250).fadeIn('fast'); }); }); (the
My code currently looks like this: private Foo myFoo; public Foo CurrentFoo { get
My code currently looks like this: <div style=position: fixed; width: 35.25%; height: 6.75%; left:
I'm currently using this code (per the codex) to show children on parent pages,
This is the code I currently use: <% Uri MyUrl = Request.UrlReferrer; if( MyUrl
I'm currently using this code to calculate the sunrise / sunset times. (To be
I am currently using this code to grab key-strokes, but I am missing e.g.
I am currently using this code to get data from a URL: NSURL *url

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.