-
Notifications
You must be signed in to change notification settings - Fork 119
Description
When a model has a one-to-many relation to another model, a race condition happens when the same instances are saved. In particular, when two process runs the code for one object in the main model, they both get the same set of instances for their related fields (for the one-to-many relation). Now, assume a new item is in the related field data. None of the processes see the the new instance, because it is not already created in the database (and it's correct). However, when the serializer starts saving the data, one process is the winner and the other one raises such an exception:
IntegrityError
duplicate key value violates unique constraint "related_field_model_pkey"
DETAIL: Key (id)=(xxxxxxxxxxxxx) already exists.
It is a common issue in django serializers. One way to fix it is to use get_or_create with defaults, so one process creates the instance and the other one see the new instance before saving it with the serializer.