MyDjango
project uses themysql
andInnoDB
engines. I have a table as shown below, thequeue
field default value is0
class Task(models.Model): task_id = models.CharField(max_length=32, primary_key=True) queue = models.IntegerField(default=0)
I have two processes, one is to insert a record based on the maximum queue in the table.
max_queue = Task.objects.all().annotate(data=Max('queue')).values('data') queue_number = max_queue[0]['data'] + 1 record = {'task_id':task_id, 'queue': queue_number} Task.objects.create(**record)
Another process is to decrement the value ofqueue
by 1for each record where
queue
query_list = Task.objects.filter(~Q(task_queue=0)) for query in query_list: Task.objects.filter(task_id=task_id).update(queue=query.queue - 1)
What I care about here iswhether these two processes occur at the same time. For example, if the subsequent process wants to decrement each value. At the same time, the first process inserts a new value. In this case, some errors may occur.
what should I do? Anyone has a good idea, thanks in advance.
You can useselect_for_update() a> for this, it will lock the record you are updating until the end of the transaction