Shashank Singh
Shashank Singh

Reputation: 657

How to lock a transaction in Django?

There is a case when request is sent multiple times to the server with same data. I want to insert that data in database using ORM of Django. In that data there is a field say 'field_imp' which can only be unique. Right now it gives me integrity error as both the request are trying to insert together. How do I avoid this condition?

How to send multiple request together?

Using terminator open multiple tabs, write the same curl request and send.

Model in Django:

class MyModel(models.Model)
    field_imp = models.TextField(unique=True)

I am using Django rest Framework for the api generation and its serializers for data's validation.

Upvotes: 0

Views: 447

Answers (2)

Shashank Singh
Shashank Singh

Reputation: 657

I used get_or_create() intead of serializer.save().

Upvotes: 1

Hayden
Hayden

Reputation: 459

The first Method is to lock table,but it is low efficiency;

The second Method is to add both two code points:

  1. add exist check into the serializer.
  2. add try...catch... for integrity error.

Upvotes: 1

Related Questions