1

I am using postgreSQL 12.

I have the following models:

class Publication(models.Model):
    title = models.CharField(max_length=30)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

...and the following TestCase classes:

class TestA(TestCase):

    @classmethod
    def setUpTestData(cls):
        p = Publication.objects.create()

        for _ in range(5):
            m = Article.objects.create()
            m.publications.add(p)

    def test_1(self):
        self.assertEqual(True, True)

class TestB(TestCase):

    @classmethod
    def setUpTestData(cls):
        print(Article.objects.all())
        for _ in range(5):
            a = Article.objects.create()
            print(a.pk)

    def test_2(self):
        self.assertEqual(True, True)

When I run these tests independently, the tests pass. When I run them together, I get the following error for the setUpTestData method under TestB:

psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "article_pkey" DETAIL: Key (id)=(1) already exists.

Further trial and error has led me to discover that this error only occurs when I include the ManyToMany relationship for TestA:

 m.publications.add(p)

The first print() statement shows an empty queryset, so the tearDownClass method for TestA appears to have worked, however the pk of the first Article is 1, which is odd as I thought because Postgres PKs are generated from Sequence objects they should never roll back.

What is happening here?

  • shouldnt the first Article pk for TestB start with 6?
  • Why does a duplicate error occur? How is this linked to the ManyToMany relationship and how can I fix this or debug it further?
alias51
  • 8,178
  • 22
  • 94
  • 166

0 Answers0