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

The Archive Base Latest Questions

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

According to (my reading of) the official dox here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated a Django QuerySet should

  • 0

According to (my reading of) the official dox here:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated

a Django QuerySet should be cached when you evaluate it. But that doesn’t seem to be the case. In the example that follows, TrackingImport is a model with a very large table behind it. (Output slightly edited for brevity.)

recs = TrackingImport.objects.filter(...stuff...)

In [102]: time(recs[0])
Wall time: 1.84 s

In [103]: time(recs[0])
Wall time: 1.84 s

Calling len() seems to work as advertised:

In [104]: len(recs)
Out[104]: 1823

In [105]: time(recs[0])
Wall time: 0.00 s

I don’t get why dereferencing the array didn’t cache the QuerySet results. It had to evaluate it, right? So what am I missing?

  • 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-16T13:33:19+00:00Added an answer on June 16, 2026 at 1:33 pm

    You can go through the source code(django.db.model.query), then you’ll be clear, here’s django 1.3.4’s query.py,

    def __getitem__(self, k):
        """
        Retrieves an item or slice from the set of results.
        """
        if not isinstance(k, (slice, int, long)):
            raise TypeError
        assert ((not isinstance(k, slice) and (k >= 0))
                or (isinstance(k, slice) and (k.start is None or k.start >= 0)
                    and (k.stop is None or k.stop >= 0))), \
                "Negative indexing is not supported."
    
        if self._result_cache is not None:
            if self._iter is not None:
                # The result cache has only been partially populated, so we may
                # need to fill it out a bit more.
                if isinstance(k, slice):
                    if k.stop is not None:
                        # Some people insist on passing in strings here.
                        bound = int(k.stop)
                    else:
                        bound = None
                else:
                    bound = k + 1
                if len(self._result_cache) < bound:
                    self._fill_cache(bound - len(self._result_cache))
            return self._result_cache[k]
    
        if isinstance(k, slice):
            qs = self._clone()
            if k.start is not None:
                start = int(k.start)
            else:
                start = None
            if k.stop is not None:
                stop = int(k.stop)
            else:
                stop = None
            qs.query.set_limits(start, stop)
            return k.step and list(qs)[::k.step] or qs
        try:
            qs = self._clone()
            qs.query.set_limits(k, k + 1)
            return list(qs)[0]
        except self.model.DoesNotExist, e:
            raise IndexError(e.args)
    

    When you not iterate through the query set, the _result_cache is None, then when you invoke resc[0], it will just skip to following lines,

    try:
       qs = self._clone()
       qs.query.set_limits(k, k + 1)
       return list(qs)[0]
    except self.model.DoesNotExist, e:
       raise IndexError(e.args)
    

    You’ll find that, in this case, the _result_cache is not being set. That’s why the duration of multiple resc[0] costs same time.

    After you invoke len(resc), you can find source code,

    def __len__(self):
        # Since __len__ is called quite frequently (for example, as part of
        # list(qs), we make some effort here to be as efficient as possible
        # whilst not messing up any existing iterators against the QuerySet.
        if self._result_cache is None:
            if self._iter:
                self._result_cache = list(self._iter)
            else:
                self._result_cache = list(self.iterator())
        elif self._iter:
            self._result_cache.extend(self._iter)
        return len(self._result_cache)
    

    You can see the _result_cache has values, then you invoke recs[0], it will just use the cache,

     if self._result_cache is not None:
             ....
         return self._result_cache[k]
    

    The souce code never lies, so it’s better to read the souce code when you don’t find your answer in documents.

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

Sidebar

Related Questions

According to this: http://msdn.microsoft.com/en-us/library/ms811053.aspx reading from a remote queue means invoking a RPC call.
According to this post: https://stackoverflow.com/questions/6666659/threading-implications-of-asynchronousbytechannel the java implementation of asynchronous socket channel doesn't guarantee
According to what I'm reading in the docs , the before_filter method is deprecated.
I was reading some C++ text at the address: http://www.parashift.com/c++-faq-lite/new/istream-and-while.html . According to the
According to the responses in Why subtract null pointer in offsetof()? (and my reading
According to this SO post: How to check the TEMPLATE_DEBUG flag in a django
I'm reading a book written by Julie Lerman on Code First. According to the
According to an article on IBM.com, a race condition is a situation in which
According to a book I'm reading, the AllowMultiple public property of AttributeUsage specifies: ...whether
Mulling over something I've been reading up on. According to Chris Webb , A

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.