Reputation: 7034
Assume I have this code:
product = Product.objects.get(name='something')
product.number_sold += 1
product.save()
if during the query number_sold was 10, and then before the save(), this code run at the same time so the query will return 10 again, it means it will save number_sold = 11 twice ? In other words, can two users running this django view can get the same value for number_sold field ?
Upvotes: 2
Views: 218
Reputation: 599926
You can do this in a single query:
Product.objects.filter(name='something').update(number_sold=F('number_sold')+1)
Upvotes: 3
Reputation: 45585
To avoid race condition in your multi-thread/process code you should use the F()-expressions
:
from django.db.models import F
product = Product.objects.get(name='something')
product.number_sold = F('number_sold') + 1
product.save()
Upvotes: 4