The Python Oracle

django not raising IntegrityError for duplicate primary key

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island

--

Chapters
00:00 Django Not Raising Integrityerror For Duplicate Primary Key
00:58 Accepted Answer Score 3
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/1446...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangotesting

#avk47



ACCEPTED ANSWER

Score 3


Your test method is wrong. What you're doing here is updating the existing instance since you're supplying an already used primary key. Change the save to a force_insert like so.

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 explain how django knows whether to UPDATE or INSERT. You should read that section.

Are you aware that django already supports automatic primary keys? See the documentation for more of an explanation.