Skip to content

Duplicated Key because of race condition in persisting related items #191

@mahmoud1468

Description

@mahmoud1468

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions