In short: using deprecate_field on ManyToMany field and then creating the model inside TransactionTestCase raises ERROR: cannot truncate a table referenced in a foreign key constraint (at least in Postgres).
Explanation:
Django's TransactionTestCase uses truncate to flush the DB after each test. truncate is called on all existing tables simultaneously to avoid issues with any of them having an FK to another (in Postgres: “truncate cannot be used on a table that has FK references from other tables, unless all such tables are also truncated in the same command”). Django searches for table names by accessing Model._meta.db_table and Model._meta.local_many_to_many . But since deprecate_field makes the field getter return None, truncate isn’t called on the table that stores many-to-many relationship. Consequently, a DB error is raised.
This sounds like a pretty niche case and not sure if it's even worth fixing, since quite a lot of stars have to align for you to experience this. Nonetheless, I decided to share to spare others the pain of debugging.
In short: using
deprecate_field
on ManyToMany field and then creating the model insideTransactionTestCase
raisesERROR: cannot truncate a table referenced in a foreign key constraint
(at least in Postgres).Explanation: Django's
TransactionTestCase
usestruncate
to flush the DB after each test.truncate
is called on all existing tables simultaneously to avoid issues with any of them having an FK to another (in Postgres: “truncate cannot be used on a table that has FK references from other tables, unless all such tables are also truncated in the same command”). Django searches for table names by accessingModel._meta.db_table
andModel._meta.local_many_to_many
. But sincedeprecate_field
makes the field getter returnNone
, truncate isn’t called on the table that stores many-to-many relationship. Consequently, a DB error is raised.This sounds like a pretty niche case and not sure if it's even worth fixing, since quite a lot of stars have to align for you to experience this. Nonetheless, I decided to share to spare others the pain of debugging.