[Answered ]-Django – Serializer throwing "Invalid pk – object does not exist" when setting ManyToMany attribute where foreign keyed object does exist

1👍

under your test/__init__.py you have to add these lines

from django.db.backends.postgresql.features import DatabaseFeatures

DatabaseFeatures.can_defer_constraint_checks = False

There’s some weird internal bug where if you operate on one table a lot with a lot of different TestCase classes then it’ll do a DB check at the end after it’s been torn down and it’ll cause an error.

I’m also using factory boy (https://factoryboy.readthedocs.io/en/stable/orms.html) to generate my test DB, which is the main reason this issue arises. The reason I believe this is because I switched out factory boy for just using <model>.objects.create() and my tests stopped failing.

Leave a comment