Why object primary keys increment between tests in Django?

There's a warning in the test documentation:

https://docs.djangoproject.com/en/dev/topics/testing/overview/

Warning If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.

Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.

Are you using django.test.TestCase or unittest.TestCase?

If you need to maintain PK integrety it seems there's an option you can try:

https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.TransactionTestCase.reset_sequences

Setting reset_sequences = True on a TransactionTestCase will make sure sequences are always reset before the test run:

class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
    reset_sequences = True

    def test_animal_pk(self):
        lion = Animal.objects.create(name="lion", sound="roar")
        # lion.pk is guaranteed to always be 1
        self.assertEqual(lion.pk, 1)

Since, django.test.LiveServerTestCase seems to subclass TransactionTestCase this probably should work for you.


You are very likely clearing the data, including the data in your database. That is not the same as recreating the database or recreating the sequences. If the sequences remain they will pick up where they left off.