﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35916	"Docs for ""Automatic primary key fields"" should mention surprising behavior"	Eric Hanchrow		"I spent a fair bit of time investigating an IntegrityError in my code, and eventually discovered that automatic primary key fields don't work *quite* as I expected.  This is not a bug, but is surprising, and thus ought to be pointed out somewhere in the docs.

Here are the details.

I have a model which uses the default automatic primary key:
{{{
class Thing(models.Model):
    def __str__(self):
        return f""Thing #{self.pk}""

}}}

I have some code which creates instances two different ways: both with, and without, specifying a primary key:

{{{
class TheOneTestCase(TestCase):
    def test_whatever(self):
        Thing.objects.create(pk=2)

        Thing.objects.create()
        Thing.objects.create()

        self.assertEqual(Thing.objects.count(), 3)

}}}

When I run this code with sqlite as the database, it passes, and creates instances with primary key values of 2, 3, and 4.

However, when I run this code with postgresql as the database, the third (i.e., the last) ""create"" call raises an exception:
{{{
django.db.utils.IntegrityError: duplicate key value violates unique constraint ""app_thing_pkey""
}}}

As best I can tell, this is not a bug; it's simply how Postgresql's sequences behave.

Anyway, since it surprised me, it might surprise other developers too, and thus ought to be mentioned somewhere in the docs."	Uncategorized	closed	Documentation	5.1	Normal	worksforme	documentation,automatic	Eric Hanchrow Adam Zapletal	Unreviewed	0	0	0	0	0	0
