[Solved]-Django test IntegrityError in fixture teardown


I have a related problem which I’ve fixed by specializing _fixture_teardown in my test case class.

_fixture_teardown is implemented in django.test.testcases to call the django command ‘flush’ which attempts to remove all data from the database. I don’t know if this is useful for you or not. In my scenario where I persist the test database and use --keepdb, it was causing problems.

As I don’t need (or want) to flush the test database, I’ve simply specialized the method to do nothing. This solves my problem and might help solve yours.


I have found the cause of the problem in very similar case. I was creating model with model_bakery. And I have this method in my ModelAdmin:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "author":
        db_field.default = request.user
        return super(PostAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs

First executed the test that was rendering of the ModelAdmin listedit view, which called this function and set the default request.user to the Post.author field.

In the next test (after request.user was already dropped from DB) I created new Post with:

baker.make("Post", title="Foo post")

Which assigned the ID of inexistent default user to the author field.

Then it throws an exception during _fixture_teardown or just simple print(post.author).

Leave a comment