Django migration on PostgreSQL stops with 'pending trigger events'
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger eventsShort answer
PostgreSQL runs a Django migration in one transaction. If the migration changes rows and then alters the same table, deferred foreign-key checks are still queued, and ALTER TABLE refuses to run. Put the data step and the schema step in separate migrations, or switch constraints to immediate before the ALTER.
Fix it fast
1Find out which cause you have
Open the migration file that failed and list its operations in order. Look for a RunPython or RunSQL followed by AddField, AlterField or similar on the same table.
python manage.py showmigrations --plan | tail -n 5 grep -n "RunPython\|RunSQL\|AlterField\|AddField" myapp/migrations/0007_*.py2Match what you see, then jump to its fix
- 1
The failing migration has a RunPython step and an ALTER-type operation, usually after a one-off default when making a field non-nullableSchema changes and RunPython sit in the same migrationFix - 2
Splitting is impractical, for example the data step and the ALTER belong together and must succeed or fail as oneYou must keep both steps in one migrationFix
- 1
What does the error look like?
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events
Cause 1 of 2
Schema changes and RunPython sit in the same migration
1Check
On PostgreSQL and SQLite every migration runs inside one transaction, and RunPython adds no transaction of its own. Django's migration documentation names this exact error as the result of mixing the two.
python manage.py sqlmigrate myapp 00072Fix
Create a separate empty migration for the data work, and keep each migration to either schema operations or data operations.
python manage.py makemigrations --empty myapp --name fill_status
# 0007: schema only (add field, null=True)
# 0008: data only (RunPython)
# 0009: schema only (make it non-nullable)3Verify
Apply the chain again.
python manage.py migrate myappConfirmed by docs.djangoproject.com
Cause 2 of 2
You must keep both steps in one migration
1Check
Django's tracker describes a migration that updated rows and then made a column non-nullable, which failed with this error because the foreign-key checks were still deferred.
python manage.py sqlmigrate myapp 00072Fix
Switch constraints to immediate before the ALTER, then back to deferred, using RunSQL operations around it. This is the workaround suggested in Django ticket 25492.
operations = [
migrations.RunPython(fill_status, migrations.RunPython.noop),
migrations.RunSQL("SET CONSTRAINTS ALL IMMEDIATE", "SET CONSTRAINTS ALL DEFERRED"),
migrations.AlterField(
model_name="order",
name="status",
field=models.CharField(max_length=20, default="pending"),
),
migrations.RunSQL("SET CONSTRAINTS ALL DEFERRED", "SET CONSTRAINTS ALL IMMEDIATE"),
]3Verify
Run the migration on a copy of the database that has rows in the table.
python manage.py migrate myappConfirmed by code.djangoproject.com
How do I stop it coming back?
- Write data migrations as their own files, as Django's migrations guide advises.
- Test migrations on PostgreSQL with realistic data, because the error depends on rows already being in the table.
- Review the output of sqlmigrate for any migration that touches rows and alters a table.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
python manage.py migrate finishes but the tables for my app are missing
relation "myapp_book" does not exist
migrate only applies migration files that exist.
3 causes, each with a fixDatabases
Django save fails on PostgreSQL: null value in a column violates a not-null constraint
django.db.utils.IntegrityError: null value in column "price" of relation "shop_product" violates not-null constraint
A model field is NOT NULL in the database unless it has null=True.
3 causes, each with a fixDatabases
psycopg2 cannot connect: connection refused on port 5432
Is the server running on that host and accepting TCP/IP connections?
Connection refused means nothing accepted the connection at the address psycopg2 tried.
3 causes, each with a fixDatabases
psycopg2 cannot resolve the host name db in Docker Compose
could not translate host name "db" to address
Compose registers each service in its own DNS under the service name, but only containers on the same Compose network can look it up.
4 causes, each with a fixDatabases
InFailedSqlTransaction: commands ignored until end of transaction block
SQLSTATE 25P02 (in_failed_sql_transaction)
Some earlier statement in the same transaction failed, and PostgreSQL ignores everything after it until you roll back.
3 causes, each with a fixDatabases
psycopg2 hangs with no timeout: connect, query and dead connections
psycopg2.errors.QueryCanceled (SQLSTATE 57014) after you set a statement timeout
Neither psycopg2 nor PostgreSQL sets a time limit by default, so a stuck connect, a slow query, a lock wait or a silently dead network link can wait forever.
4 causes, each with a fix