Django-DB-Migrations: cannot ALTER TABLE because it has pending trigger events

前端 未结 6 1366
梦毁少年i
梦毁少年i 2020-12-02 10:45

I want to remove null=True from a TextField:

-    footer=models.TextField(null=True, blank=True)
+    footer=models.TextField(blank=True, default=\'\')
         


        
6条回答
  •  时光取名叫无心
    2020-12-02 11:27

    On PostgreSQL and SQLite, this problem can occur if you have a sufficiently complex RunPython command combined with schema alterations in the same migration. For example, if you are adding a non-nullable field, the typical migration steps for this is:

    1. AddField to add the field as nullable
    2. RunRython to populate it
    3. AlterField to change the field to be non-nullable

    On SQLite and Postgres, this can cause problems because the whole thing is being done in one transaction.
    The Django docs have a specific warning about this:

    On databases that do support DDL transactions (SQLite and PostgreSQL), RunPython operations do not have any transactions automatically added besides the transactions created for each migration. Thus, on PostgreSQL, for example, you should avoid combining schema changes and RunPython operations in the same migration or you may hit errors like OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events.

    If this is the case, the solution is to separate your migration into multiple migrations. In general, the way to split is to have a first migration containing the steps up through the run_python command and the second migration containing all the ones after it. Thus, in the case described above, the pattern would be the AddField and RunPython in one migration, and the AlterField in a second.

提交回复
热议问题