Working with Celery and Django Database Transactions
In this article, we'll look at how to prevent a Celery task dependent on a Django database transaction from executing before the database commits the transaction. This is a fairly common issue.
Objectives
After reading, you should be able to:
- Describe what a database transaction is and how to use it in Django
- Explain why you might get a
DoesNotExist
error in a Celery worker and how to solve it - Prevent a task from executing before the database commits a transaction
What is a database transaction?
A database transaction is a unit of work that is either committed (applied to the database) or rolled back (undone from the database) as a unit.
Most databases use the following pattern:
- Begin the transaction.
- Execute a set of data manipulations and/or queries.
- If no error occurs, then commit the transaction.
- If an error occurs, then roll back the transaction.
As you can see, a transaction is a very useful way to keep your data far away from chaos.
Back to Top