I am using postgreSQL 12.
I have two TestCase classes:
class TestA(TestCase):
    @classmethod
    def setUpTestData(cls):
        for _ in range(5):
            MyModel.objects.create()
    def test_1(self):
        print('Start test 1')
        objects = MyModel.objects.all()
        for i in objects:
            print(i.pk)
        self.assertEqual(True, True)
class TestB(TestCase):
    @classmethod
    def setUpTestData(cls):
        for _ in range(5):
            MyModel.objects.create()
    def test_2(self):
        print('Start test 2')
        objects = MyModel.objects.all()
        for i in objects:
            print(i.pk)
        self.assertEqual(True, True)
This results in printing:
Start test 1
1 2 3 4 5
Start test 2
6 7 8 9 10
When these tests are run it is clear that although the tearDownClass is removing the objects, the autoincrement on primary key is not being reset.
Indeed, if I try to set MyModel.objects.create(pk=1) on test_2 then I get a duplicate key value error.
This causes problems if you use something like factory_boy to create your fixtures, as it will throw similar duplicate key errors.
Why are primary keys not removed and how to I fix this situation?
 
     
    