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 8659957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T16:08:10+00:00 2026-06-12T16:08:10+00:00

I’ve got a Django view that I’m trying to optimise. It shows a list

  • 0

I’ve got a Django view that I’m trying to optimise. It shows a list of parent objects on a page, along with their children. The child model has the foreign key back to the parent, so select_related doesn’t seem to apply.

class Parent(models.Model):
    name = models.CharField(max_length=31)

class Child(models.Model):
    name = models.CharField(max_length=31)
    parent = models.ForeignKey(Parent)

A naive implementation uses n+1 queries, where n is the number of parent objects, ie. one query to fetch the parent list, then one query to fetch the children of each parent.

I’ve written a view that does the job in two queries – one to fetch the parent objects, another to fetch the related children, then some Python (that I’m far too embarrassed to post here) to put it all back together again.

Once I found myself importing the standard library’s collections module I realised that I was probably doing it wrong. There is probably a much easier way, but I lack the Django experience to find it. Any pointers would be much appreciated!

  • 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-12T16:08:11+00:00Added an answer on June 12, 2026 at 4:08 pm

    Add a related_name to the foreign key, then use the prefetch_related method which added to Django 1.4:

    Returns a QuerySet that will automatically retrieve, in a single
    batch, related objects for each of the specified lookups.

    This has a similar purpose to select_related, in that both are
    designed to stop the deluge of database queries that is caused by
    accessing related objects, but the strategy is quite different:

    • select_related works by creating a SQL join and including the fields
      of the related object in the SELECT statement. For this reason,
      select_related gets the related objects in the same database query.
      However, to avoid the much larger result set that would result from
      joining across a ‘many’ relationship, select_related is limited to
      single-valued relationships – foreign key and one-to-one.

    • prefetch_related, on the other hand, does a separate lookup for each
      relationship, and does the ‘joining’ in Python. This allows it to
      prefetch many-to-many and many-to-one objects, which cannot be done
      using select_related, in addition to the foreign key and one-to-one
      relationships that are supported by select_related. It also supports
      prefetching of GenericRelation and GenericForeignKey.

    class Parent(models.Model):
        name = models.CharField(max_length=31)
    
    class Child(models.Model):
        name = models.CharField(max_length=31)
        parent = models.ForeignKey(Parent, related_name='children') 
    
    
    >>> Parent.objects.all().prefetch_related('children')
    

    All the relevant children will be fetched in a single query, and used
    to make QuerySets that have a pre-filled cache of the relevant
    results. These QuerySets are then used in the self.children.all()
    calls.

    Note 1 that, as always with QuerySets, any subsequent chained methods which imply a different database query will ignore previously
    cached results, and retrieve data using a fresh database query.

    Note 2 that if you use iterator() to run the query, prefetch_related() calls will be ignored since these two
    optimizations do not make sense together.

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

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
Basically, what I'm trying to create is a page of div tags, each has
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into

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.