Hi all,
I’m Lakshya Soni, a 2nd year student at IIT Bhilai, new to contributing to Django. I’ve set up the development environment, worked through the contributing tutorial, and have been reading the migrations code looking for something I could help with.
I spent some time on #31255 (Migrations create a redundant RemoveField operation when deleting 2 models with related fields) and wanted to check my understanding before going any further.
Reproduced on current main (6.2.dev) — deleting two models that both have an FK to a third model that is kept:
BEFORE optimize: RemoveField(modelb.related_field),
RemoveField(modelc.related_field),
DeleteModel(ModelB), DeleteModel(ModelC)
AFTER optimize: RemoveField(modelc.related_field),
DeleteModel(ModelB), DeleteModel(ModelC)
ModelB’s RemoveField is folded into its DeleteModel, but ModelC’s is not, because DeleteModel(ModelB) sits between them and DeleteModel.references_model() returns True unconditionally, which blocks both the left and right reductions in optimize_inner.
What I tried: narrowing DeleteModel.references_field() so it only matches its own model. My regression test passed, but five existing tests failed — test_non_circular_foreignkey_dependency_removal, test_m2m_w_through_multistep_remove, test_many_to_many_removed_before_through_model_2, test_remove_field_with_model_options, and test_makemigrations_update. So the conservative behaviour is clearly load-bearing for FK ordering, and I reverted it.
Reading back through the ticket, comment:13 mentions the same many-to-many failures, so it looks like I walked into a wall that was already documented five years ago.
My question: comment:19 suggests changing Operation.reduce() to take a ProjectState so the optimizer can tell what is actually being referenced. Is that still the intended direction? And is this a reasonable ticket for a newer contributor to attempt, or is the API change too broad a place to start?
If it’s useful, I’m happy to add the reproduction above to the ticket so the next person doesn’t have to redo it.
Thanks!
Even though I used Claude to help with the investigation, but I ran everything locally and verified the test results myself.