0

I have some records in a django Model, and each time I want to query and update some of them. How can perform this operation atomically?

def queryAndUpdate(count):
    entries = Model.objects.filter(...)[:count]
    for entry in entries:
        entry.count = F('count') + 1
        entry.save()
    return entries

I tried QuerySet.select_for_update(), but it fails.

lishowie
  • 3
  • 2

1 Answers1

1

Just:

Model.objects.filter(...).update(count=F('count') + 1)

Here is the doc.

If you want to limit the size of QuerySet as 100, use Model.objects.filter(...)[:100]. It will be translated to SELECT ... LIMIT 100, so you don't need to worry about the performance, here is another question about this.

And it's return value is <class 'django.db.models.query.QuerySet'>, same as Model.objects.filter(...), so you can use Model.objects.filter(...)[:100].update(...) too.

Community
  • 1
  • 1
WKPlus
  • 6,955
  • 2
  • 35
  • 53