Opened 2 years ago

Last modified 2 months ago

#33586 new Bug

Cannot delete object (A) referenced by another object (B) if said object (A) has a foreign key to a custom User model — at Version 2

Reported by: Jeremy Poulin Owned by: nobody
Component: Migrations Version: 4.0
Severity: Normal Keywords:
Cc: Simon Charette, Ülgen Sarıkavak Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description (last modified by Jeremy Poulin)

I've created a reproducer app:
https://github.com/jaypoulz/rmigration_bug

After installing dependencies, run the repro.sh script:
https://github.com/jaypoulz/rmigration_bug/blob/main/repro.sh

All this script does is clear the DB, run the initial migrations (which will fail because no user exists yet), create a dummy superuser, re-run the migration so that it completes, and then run a reverse migration.

Object A has a single foreign key to a custom User object.
Object B has a foreign key (many to one) relationships to object A. This object never needs to be instantiated, and in fact, only exists to trigger a mismatch in 'Fake' model comparison during the delete call.

https://github.com/jaypoulz/rmigration_bug/blob/main/rmigrate/migrations/0002_create_sample_objects.py#L15

ValueError: Cannot query "A object (1)": Must be "A" instance.

This appears to be because delete first checks if object A is referenced by any models that have a CASCADE on delete relationship, and discovers object B. It then compares the model identifier of object B's reference to object A with the instance type of the object that is going to be deleted (also object A).

For some reason, these identifiers do not match.

In other words, Even though there are no instances of B, A cannot be deleted because the model type returned by A via model lookup is not the same as the model type referenced by B.

For some reason, this only occurs when you have a custom User model.

If you comment out the User model, the issue no longer occurs. I've created a branch to prove this as well:
https://github.com/jaypoulz/rmigration_bug/compare/no-custom-user

Change History (2)

comment:1 by Jeremy Poulin, 2 years ago

Description: modified (diff)
Summary: Cannot delete object with a foreign key dependency if the object also has a foreign key to a custom User modelCannot delete object (A) referenced by another object (B) if said object (A) has a foreign key to a custom User model

comment:2 by Jeremy Poulin, 2 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top