Django does not raise IntegrityError for duplicate primary key

Does django use uniqueness for primary key?

The documentation here seems to suggest so, but when I define the class as:

class Site(models.Model):
    id = models.IntegerField(primary_key=True)

      

and check this limitation in a test case:

class SiteTestCase(TestCase):
    def setUp(self):
        self.site = Site(id=0, name='Site')
        self.site.save()

    def tearDown(self):
        self.site.delete()

    def test_unique_id(self):
        with self.assertRaises(IntegrityError):
            badSite = Site(id=0, name='Bad Site')
            badSite.save()
            badSite.delete()

      

test fails.

If I test for a normal field (primary_key = False, unique = True) then the exception is thrown correctly. Setting unique = True on the id field does not change the result.

Is there something about the primary_key fields that I'm missing here?

My database is MySQL if relevant.

+3


source to share


1 answer


Your testing method is wrong. What you are doing here is updating the existing instance as you are using the already used primary key. Change save

to force_insert

like this.

def test_unique_id(self):
        with self.assertRaises(IntegrityError):
            badSite = Site(id=0, name='Bad Site')
            badSite.save(force_insert=True)
            badSite.delete()

      



The django docs explains how django knows whether to UPDATE or INSERT . You should read this section.

Did you know that django already supports automatic primary keys? See the documentation for details .

+2


source







All Articles