Opened 6 months ago

Closed 6 months ago

#35416 closed Bug (duplicate)

Removing a primary_key field causes a migration crash

Reported by: Sarah Boyce Owned by: nobody
Component: Migrations Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

[I am using SQLite]

Create a model with a primary_key field and makemigrations and migrate

from django.db import models


class MySimpleModel(models.Model):
    some_pk = models.IntegerField(primary_key=True)

Then remove the field and makemigrations

class MySimpleModel(models.Model):
    pass

This prompts you to supply a default because

It is impossible to add a non-nullable field 'id' to mysimplemodel without specifying a default.

If you supply a default, you get a migration like this:

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('app3', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='mysimplemodel',
            name='some_pk',
        ),
        migrations.AddField(
            model_name='mysimplemodel',
            name='id',
            field=models.BigAutoField(auto_created=True, default=1, primary_key=True, serialize=False, verbose_name='ID'),
            preserve_default=False,
        ),
    ]

This crashes when you migrate with:

django.db.utils.OperationalError: near ")": syntax error

But if you remove the provided default from the migration and switch the order so that the field is added before the previous primary_key field is removed, the migration can be applied.

This is very similar to #22997 and certainly related (they didn't remove the field but instead altered the field to no longer be a primary_key in that ticket).
I am not sure whether to class this as a duplicate and require a fix as part of #22997 - happy to hear opinions here.

Change History (3)

comment:1 by Sarah Boyce, 6 months ago

Type: UncategorizedBug

comment:2 by Simon Charette, 6 months ago

I would qualify this as a duplicate of #22997 as changing a model from

class MySimpleModel(models.Model):
    some_pk = models.IntegerField(primary_key=True)

to

class MySimpleModel(models.Model):
    pass

Is exactly removing an explicit primary key.

The ticket also describes the questioner asking about providing a default value.

I think that your first instinct was right, this is the same issue which is not specific to Postgres.

comment:3 by Sarah Boyce, 6 months ago

Resolution: duplicate
Status: newclosed

Thank you for verifying - duplicate of #22997.

Note: See TracTickets for help on using tickets.
Back to Top