0

There is a queue of tasks for humans. I want to take one unfulfilled task from the queue and assign an executor. I use update() and nested query to prevent a race condition.

sliced_queryset = Tasks.objects.filter(done=False, executor__isnull=True)[:1]
task = Tasks.objects.filter(id__in=sliced_queryset).update(executor=request.user)

update() returns the number of rows matched. I want to have updated object in task variable. Any ideas?

  • Well usually a view is wrapped in a single transaction if I recall correctly, hence first querying then updating should be safe, since other views work with another transaction. If you do the database queries in a transaction, then they only take *effect* when you end the transaction. So in your view it looks like the transactions are done, but other concurrent transactions can not influence that. – Willem Van Onsem May 20 '18 at 13:21
  • See: https://stackoverflow.com/q/6477574/67579 – Willem Van Onsem May 20 '18 at 13:23
  • Do you want the *number* of rows updated, or the rows itself? – Willem Van Onsem May 20 '18 at 13:26
  • @WillemVanOnsem `Well usually a view is wrapped in a single transaction ` is that true? – itzMEonTV May 20 '18 at 13:30
  • @itzMEonTV: given the `ATOMIC_REQUESTS` setting is set to True: https://docs.djangoproject.com/en/2.0/topics/db/transactions/#tying-transactions-to-http-requests – Willem Van Onsem May 20 '18 at 13:31

0 Answers0