My problem is as follows:
I have a car dealer A, and a db table named sold_cars. When a car is being sold I create entry in this table.
Table ha
I would recommend using the F() expression instead of locking the entire table. If your app is being heavily used, locking the table will have significant performance impact.
The exact scenario you described is mentioned in Django documentation here. Based on your scenario, here's the code you can use:
from django.db.models import F
# Populate sold_cars as you normally do..
# Before saving, use the "F" expression
sold_cars.order_num =F('order_num') + 1
sold_cars.save()
# You must do this before referring to order_num:
sold_cars.refresh_from_db()
# Now you have the database-assigned order number in sold_cars.order_num
Note that if you set order_num during an update operation, use the following instead:
sold_cars.update(order_num=F('order_num')+1)
sold_cars.refresh_from_db()
Since database is in charge of updating the field, there won't be any race conditions or duplicated order_num values. Plus, this approach is much faster than one with locked tables.