#33919 closed Bug (fixed)
Primary keys added in non-initial migration are not created as identity columns in PostgreSQL
| Reported by: | jackcbrown89 | Owned by: | Mariusz Felisiak | 
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 4.1 | 
| Severity: | Release blocker | Keywords: | postgres | 
| Cc: | Florian Apolloner, Michael Kany | Triage Stage: | Accepted | 
| Has patch: | yes | Needs documentation: | no | 
| Needs tests: | no | Patch needs improvement: | no | 
| Easy pickings: | no | UI/UX: | no | 
Description (last modified by )
In this example, a model was created initially with a primary key on a one-to-one field. The primary key was then moved to a new AutoField. This was working prior to the 4.1 release.
## models.py
class Example(models.Model):
    old_id = models.OneToOneField(
        OtherModel,
        on_delete=models.CASCADE,
        ## primary_key=True,  <--- used to be the primary key
    )
    id = models.AutoField(primary_key=True) # <--- new primary key
Running sqlmigrate on the migration where the primary key changes reveals that the "id" column does not autogenerate values:
$ python manage.py sqlmigrate example 0002 BEGIN; -- -- Add field id to example -- ALTER TABLE "example" ADD COLUMN "id" integer NOT NULL PRIMARY KEY; -- -- Alter field old_id on example -- ALTER TABLE "example" ALTER COLUMN "old_id" DROP NOT NULL;
When it should be
$ python manage.py sqlmigrate example 0002 BEGIN; -- -- Add field id to example -- ALTER TABLE "example" ADD COLUMN "id" integer NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY; -- -- Alter field old_id on example -- ALTER TABLE "example" ALTER COLUMN "old_id" DROP NOT NULL;
This seems to be related to the changes made here: https://code.djangoproject.com/ticket/30511
PR: https://github.com/django/django/pull/15542
Change History (6)
comment:1 by , 3 years ago
| Description: | modified (diff) | 
|---|
comment:2 by , 3 years ago
| Component: | Migrations → Database layer (models, ORM) | 
|---|---|
| Severity: | Normal → Release blocker | 
| Triage Stage: | Unreviewed → Accepted | 
| Type: | Uncategorized → Bug | 
comment:3 by , 3 years ago
| Owner: | changed from to | 
|---|---|
| Status: | new → assigned | 
  Note:
 See   TracTickets
 for help on using tickets.
    
Thanks for the report! Column suffixes (as
GENERATED BY...) should be used when adding a new field:django/db/backends/base/schema.py
Regression in 2eea361eff58dd98c409c5227064b901f41bd0d6.