[Fixed]-Django.db.utils.OperationalError: cannot ALTER TABLE because it has pending trigger events

16👍

This error seems to happen when trying to update and change schema of the same table in one operation.

For example, after providing new default values when prompted by makemigrations when removing null=True from a field, this error seems to appear because Django is trying to change nullability while also updating the column.

Workarounds, depending on situation:

  • Easiest is often adding a new field with the desired properties, then removing the old field (maybe after copying data over).
  • If the error can be avoided by setting values for all fields that were needing a new default value (Django asking during the migration), try setting those values before making the migration/schema change.

In your specific case, adding a new field then removing the old is probably the way to go.

4👍

Adding to Max Lemieux’s answer, if you try to change a field from nullable to non-nullable, this is impossible in the same database transaction, thus:

  • you can split your operations into 2 migrations (not recommended if complex operations)
  • you can wrap your migration’s operations with these two statements to force PostgreSQL to check null constraint on save and not at the end of transaction
    operations = [
        migrations.RunSQL('SET CONSTRAINTS ALL IMMEDIATE', reverse_sql='SET CONSTRAINTS ALL DEFERRED'),
        ... # your other operations here
        migrations.RunSQL('SET CONSTRAINTS ALL DEFERRED', reverse_sql='SET CONSTRAINTS ALL IMMEDIATE'),
    ]
    

Leave a comment