pythondjangodjango-testingtestcasedjango-fixtures

Django test with fixtures gives ForeignKeyViolation or IntegrityError


I am trying to write test cases for the Django RestAPI that we have but I have an issue with the fixtures loading. Everything works correctly when I have only one TestCase but when I add a second TestCase in a second django app I get django.db.utils.IntegrityError. My original intention was to create a general TestCase where I set up the most used objects in the setUpTestData function and make the other tests inherit from that one.

Things I have tried:

When I comment one of the test files the other works and vice-versa. When I used the call_command with verbose=2, the fixtures in the first file executed work perfectly, and it breaks just when trying to install the first fixture of the second file, with the error:

django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "preference_questions" violates foreign key constraint "preference_questi_preference_questi_64f61c66_fk_prefer" DETAIL:  Key (preference_question_category_id)=(2) is not present in table "preference_question_category"

Sometimes it gives ForeignKeyViolation depending on the case of the above mentioned.


Solution

  • Turns out the issue was that the fixtures had IDs on them, those IDs cannot be removed because objects had relations between them. In this case, there are two options I found:

    Depending on your case it may be more interesting to use one or the other. Nonetheless, the first one is the best probably.