SerialFields - Yay or Nay?

Thanks @nessita !

To progress this ticket, we need someone to take ownership and propose an outline for the implementation, so it can be moved to “Accepted” and enter the review process.

I was planning on pushing this further once composite primary keys are merged.
IMO an AutoField should either be a primary key OR part of a composite primary key.

I’m not sure about the other use case. I don’t think IDENTITY is suitable for DB counters.

GENERATED ALWAYS AS IDENTITY would, wouldn’t it? This was my thinking:

psql (16.3)
Type "help" for help.

djangotest=# CREATE TABLE example_table (
    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    description TEXT NOT NULL,
    counter INTEGER GENERATED ALWAYS AS IDENTITY
);
CREATE TABLE
djangotest=# INSERT INTO example_table (description) VALUES ('First entry');
INSERT INTO example_table (description) VALUES ('Second entry');
INSERT INTO example_table (description) VALUES ('Third entry');
INSERT 0 1
INSERT 0 1
INSERT 0 1
djangotest=# SELECT * FROM example_table;
 id | description  | counter 
----+--------------+---------
  1 | First entry  |       1
  2 | Second entry |       2
  3 | Third entry  |       3
(3 rows)

Yes I understand. What I meant is IDENTITY was meant to identify a row. That’s why the other databases only allow one per table. Maybe Postgres is a little too flexible in this regard.

My two cents here,

I would never create the serial fields as ALWAYS, as BY DEFAULT suffices.

In regards to the SerialFields, I believe this is a good feature to have for one more reason to the above mentioned, which is when a PK has been historically created in other ways (UUIDField for example), and developers are now looking to have a PK that is serialized. SerialField can be used to bridge this gap between having another PK and migrating to a serial field.

The main reason for this is that although most PKs are user/django generated, SerialField for a new pk would need to come from a serial field, however adding the new PK to an existing model with an existing PK is impossible. This feature would ease the migration process a lot.

Here’s the follow-up ticket: #35957 (Allow AutoFields in composite primary keys) – Django

3 Likes