Iterating over a set of queries, for example:
class Book(models.Model):
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()
... works just fine. However, this is a cron task. book.viewsincreases while this happens. If book.viewsmodified while this cronjob is running, it returns.
Now book.viewscronjob does not change, but it is cached during the request call .all(). When book.save(), I feel like he is using the old meaning book.views.
Is there a way to make sure that only the field is updated activity? As an alternative, let's say there are 100,000 books. This will take quite some time. But it book.viewswill be from the moment the request starts. Is the solution easy to use .iterator()?
: , . , , .
def calculate_statistics(self):
self.activity = self.views + self.hearts.count() * 2
self.activity += Comment.objects.for_model(self).count() * 4
self.save()