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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:59:35+00:00 2026-05-20T10:59:35+00:00

I have a task which needs to be run on ‘most’ objects in my

  • 0

I have a task which needs to be run on ‘most’ objects in my database once every some period of time (once a day, once a week, whatever). Basically this means that I have some query that looks like this running in it’s own thread.

for model_instance in SomeModel.objects.all():
    do_something(model_instance)

(Note that it’s actually a filter() not all() but none-the-less I still end up selecting a very large set of objects.)

The problem I’m running into is that after running for a while the thread is killed by my hosting provider because I’m using too much memory. I’m assuming all this memory use is happening because even though the QuerySet object returned by my query initially has a very small memory footprint it ends up growing as the QuerySet object caches each model_instance as I iterate through them.

My question is, “what is the best way to iterate through almost every SomeModel in my database in a memory efficient way?” or perhaps my question is “how do I ‘un-cache’ model instances from a django queryset?”

EDIT: I’m actually using the results of the queryset to build a series of new objects. As such, I don’t end up updating the queried-for objects at all.

  • 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-05-20T10:59:36+00:00Added an answer on May 20, 2026 at 10:59 am

    So what I actually ended up doing is building something that you can ‘wrap’ a QuerySet in. It works by making a deepcopy of the QuerySet, using the slice syntax–e.g., some_queryset[15:45]–but then it makes another deepcopy of the original QuerySet when the slice has been completely iterated through. This means that only the set of Objects returned in ‘this’ particular slice are stored in memory.

    class MemorySavingQuerysetIterator(object):
    
        def __init__(self,queryset,max_obj_num=1000):
            self._base_queryset = queryset
            self._generator = self._setup()
            self.max_obj_num = max_obj_num
    
        def _setup(self):
            for i in xrange(0,self._base_queryset.count(),self.max_obj_num):
                # By making a copy of of the queryset and using that to actually access
                # the objects we ensure that there are only `max_obj_num` objects in
                # memory at any given time
                smaller_queryset = copy.deepcopy(self._base_queryset)[i:i+self.max_obj_num]
                logger.debug('Grabbing next %s objects from DB' % self.max_obj_num)
                for obj in smaller_queryset.iterator():
                    yield obj
    
        def __iter__(self):
            return self
    
        def next(self):
            return self._generator.next()
    

    So instead of…

    for obj in SomeObject.objects.filter(foo='bar'): <-- Something that returns *a lot* of Objects
        do_something(obj);
    

    You would do…

    for obj in MemorySavingQuerysetIterator(in SomeObject.objects.filter(foo='bar')):
        do_something(obj);
    

    Please note that the intention of this is to save memory in your Python interpreter. It essentially does this by making more database queries. Usually people are trying to do the exact opposite of that–i.e., minimize database queries as much as possible without regards to memory usage. Hopefully somebody will find this useful though.

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

Sidebar

Related Questions

I have a task that needs to run every 30 seconds. I can do
I have a backroundrb scheduled task that takes quite a long time to run.
I have a task which I need to run in the background in my
Scenario I have an web application which needs some calculations and processing on data.
The task I have iS, I have a source is the CSV which needs
We have a vxWorks design which requires one task to process messages from two
We have MS Sharepoint -- which isn't all bad for managing a task list.
I have a task and I want to generate some code using the CodeDom.
I have a Task object that has a collection of Label objects ... in
I'm creating an console application which needs to run several threads in order to

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.