Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating over a large Django queryset while the data is changing elsewhere
    primarykey
    data
    text
    <p>Iterating over a queryset, like so:</p> <pre><code>class Book(models.Model): # &lt;snip some other stuff&gt; activity = models.PositiveIntegerField(default=0) views = models.PositiveIntegerField(default=0) def calculate_statistics(): self.activity = book.views * 4 book.save() def cron_job_calculate_all_book_statistics(): for book in Book.objects.all(): book.calculate_statistics() </code></pre> <p>...works just fine. However, this is a cron task. <code>book.views</code> is being incremented while this is happening. If <code>book.views</code> is modified while this cronjob is running, it gets reverted.</p> <p>Now, <code>book.views</code> is not being modified by the cronjob, but it is being cached during the <code>.all()</code> queryset call. When <code>book.save()</code>, I have a feeling it is using the old <code>book.views</code> value.</p> <p>Is there a way to make sure that only the <code>activity</code> field is updated? Alternatively, let's say there are 100,000 books. This will take quite a while to run. But the <code>book.views</code> will be from when the queryset originally starts running. Is the solution to just use an <code>.iterator()</code>?</p> <p><strong>UPDATE:</strong> Here's effectively what I am doing. If you have ideas about how to make this work well inline, then I'm all for it.</p> <pre><code>def calculate_statistics(self): self.activity = self.views + self.hearts.count() * 2 # Can't do self.comments.count with a comments GenericRelation, because Comment uses # a TextField for object_pk, and that breaks the whole system. Lame. self.activity += Comment.objects.for_model(self).count() * 4 self.save() </code></pre>
    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. 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