Skip to content

Conversation

@bckohan
Copy link

@bckohan bckohan commented Jan 19, 2026

Description

#2567 documents intermittent failures on tests involving the polymorphic models in the sponsors directory. The exception is always along the lines of:

psycopg2.errors.ForeignKeyViolation: insert or update on table "..." violates foreign key constraint "..."
DETAIL:  Key (polymorphic_ctype_id)=(100) is not present in table "django_content_type".

django-polymorphic uses the polymorphic_ctype field to track the concrete instance type on the base table. It sets this field automatically. Whats happening here is that model bakery is overriding this field and setting it to a random content type. Most of the time this passed the foreign key constraint - but ContentType objects are cached and mailing/tests/models.py created a temporary model (MockEmailTemplate) in a transaction that is rolled back after the mailing tests are complete. The cache that model bakery was drawing content types from was not cleared however. You get the fk constraint error when it happened to randomly set the content type of a polymorphic model to MockEmailTemplate.

There are two parts to the fix here:

  1. I explicitly clear the ContentType cache after the mailing tests run. This is not strictly necessary because 2 fixes the real problem.
  2. I configure the test to use a custom model baker class that detects polymorphic models and ignores the polymorphic_ctype field on them, allowing the base class to set it properly. I think this is the best approach because:
    • I looked into using recipes but you'd have to specify a recipe for each polymorphic model type and the diff in the tests would be huge.
    • This method will also work for any future accidental uses of baker.make(PolymorphicModel).
    • It is my hope that a future major release of django-polymorphic will no longer rely on the contenttypes framework, eliminating the need for special model bakery logic for polymorphic models.

Closes

@bckohan bckohan changed the title Fix tests: Fix tests: Intermittent FK constraint violation on polymorphic_ctype_id Jan 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant