Opened 3 weeks ago

Last modified 3 weeks ago

#37497 assigned Bug

migrations.AddField(field=models.ForeignObject(...)) doesn't migrate backwards on SQLite

Reported by: BestCrazyNoob Owned by: Abdulhafiz Davlatov
Component: Migrations Version: 6.1
Severity: Normal Keywords: ForeignObject, sqlite
Cc: BestCrazyNoob, Abdulhafiz Davlatov Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

As per title, migrations that add a ForeignObject to a model crash when migrating backwards.

Example models:

from django.db import models

class A(models.Model):
    x = models.BigIntegerField(
        unique=True,
    )

class B(models.Model):
    x = models.BigIntegerField()
    ref = models.ForeignObject(
        A,
        on_delete=models.DO_NOTHING,
        from_fields=("x"),
        to_fields=("x"),
        null=True,
    )

To reproduce:

  • Create A and B with only the field 'x';
  • makemigrations && migrate;
  • Add the ForeignObject;
  • makemigrations && migrate;
  • migrate back to the previous state.

Traceback:

  File ".../lib/python3.13/site-packages/django/db/migrations/migration.py", line 193, in unapply
    operation.database_backwards(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self.app_label, schema_editor, from_state, to_state
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File ".../lib/python3.13/site-packages/django/db/migrations/operations/fields.py", line 128, in database_backwards
    schema_editor.remove_field(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^
        from_model, from_model._meta.get_field(self.name)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File ".../lib/python3.13/site-packages/django/db/backends/sqlite3/schema.py", line 350, in remove_field
    and not (field.remote_field and field.db_constraint)
                                    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'ForeignObject' object has no attribute 'db_constraint'

Change History (2)

comment:1 by Jacob Walls, 3 weeks ago

Component: Database layer (models, ORM) → Migrations
Keywords: ForeignObject sqlite added
Summary: migrations.AddField(field=models.ForeignObject(...)) doesn't migrate backwards → migrations.AddField(field=models.ForeignObject(...)) doesn't migrate backwards on SQLite
Triage Stage: Unreviewed → Accepted

Thanks! Reproduced at 9102fd76e3af8f9b0aeffc724f17fa3690236138 on sqlite. Postgres was fine. Would you like to submit a PR?

comment:2 by Abdulhafiz Davlatov, 3 weeks ago

Cc: Abdulhafiz Davlatov added
Has patch: set
Owner: set to Abdulhafiz Davlatov
Status: new → assigned
Note: See TracTickets for help on using tickets.
Back to Top