Knower
Helping DB with transaction

Transaction

Introduction

Django is basically adopting autocommit method so when each query is executed it will commit on database right away (opens in a new tab). Due to this feature, our database can produce unwanted increment of pk or id of each queryset that Django automatically provides although users provided invalid data.

Why Django is using autocommit

According to the SQL standards, developers must explicitly carry out commit or roll-back when each SQL query starts transaction. This will lead to bad developer experience, and thus Django is using autocommit method to alleviate this problem.

To stop this, we can use Transaction (opens in a new tab) that Django provides. By using Transaction, all changes on database will be stopped whenever errors occur while querysets are being created.

We can apply Transaction partially on views, but results will be same.

⚠️

However, Django official documentation is warning that if traffic increases Transaction will cause poor performance. Dropping performance will be affected by query patterns or how database locking is well executed.