A database transaction is a single, indivisible unit of work that maintains data consistency and ensures reliability. Management of transactions is crucial not only in Django but in other web frameworks as well because the integrity and consistency of the data entirely depend on it.
In web applications, requests can be made to modify the records in a database, but if those requests are not appropriately managed, they can cause serious problems.
Let’s make an analogy where we have two users, User A and User B. User A wants to send money to User B. However, due to some transaction discrepancies, the money sent by User A supposedly gets subtracted from the database but User B doesn’t receive it, i.e., it does not get added to User B’s current amount. To counter this problem, Django can perform atomic transactions.
Atomic transactions can roll back an entire transaction if things go wrong.
The syntax to perform an atomic transaction in Django is as follows.
def view(request):with transaction.atomic():# database queries
Let’s look at a code example where we perform an atomic transaction to transfer some amount between User A and User B.
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
The transaction.atomic()
function is defined at line 25 in the my_project/my_app/views.py
file.
transaction.atomic()
function ensures that all the database operations within a transaction are executed or not at all.Click “Run” to run and interact with the application.
The app has three input fields, i.e., "sender"
, "receiver"
, and "money"
.
Below the input fields, each user’s current balance is shown.
To transfer funds:
"user_1"
in the first input field."user_2"
in the second input field.