I have a simple database relationship: one Item relates to many ItemDetails. ItemDetails are updated all at once: a message comes in via HTTP POST with the full set of ItemDetails to replace any old ItemDetails with. The logic I use is this:
with transaction.atomic():
...
ItemDetails.objects.filter(item_id=item_id).all().delete()
for item in new_item_list:
ItemDetails.objects.create(title=item.title, ...)
But this seems to have a race condition if two senders send an update at the same time. I sometimes see duplicated lists, since (I think) the delete() is running on two threads in more or less parallel and then the creates happen.
What locking strategy can I use to avoid this problem? I am using Django with PostgreSQL.