Does django enforce uniqueness for a primary key?
The documentation here seems to suggest so, but when I define a class as:
class Site(models.Model):
id = models.IntegerField(primary_key=True)
and test this constraint 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()
the test fails.
If I test on a normal field (primary_key=False, unique=True) then the exception is raised correctly. Setting unique=True on the id field does not change the result.
Is there something about primary_key fields that I'm missing here?
My database backend is MySQL, if that's relevant.
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.