﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34673	Migrations ordering: add constraint run_immediately_after	Matevž Poljanc	nobody	"Problem: after moving models from one app to the other, completely unrelated migrations using RunPython can fail

Details: as our code base is growing, we wanted to refactor the code and split one app (say A) into multiple apps (B and C) (to keep clean separation, reduce interdependency and promote reusability). Because tables were big, we decide to use SeparateDatabaseAndState way (renaming tables in SQL, ""deleting"" and ""creating"" models in Python). We have model FirstModel in app A, which we moved to app B using the procedure. This model is also referenced by foreign key on model SecondModel in another app D and have migration which ""reconnects"" FK from FirstModel app A to FirstModel in app B. 

We have the following migrations (in correct dependency order):
1. in app A: SeparateDatabaseAndState to rename table in database from a_firstmodel to b_firstmodel and ""delete"" FirstModel in app A
2. in app B: SeparateDatabaseAndState to create FirstModel in app B and do nothing in the db
3. in app D: SeparateDatabaseAndState to do nothing in db and ""connect"" FK field to FirstModel in B

This works well on its own. Now let's add completely unrelated app E, with a migration 0001 using RunPython and no dependencies on any of the other apps. If migration 0001 is run between migrations 2. and 3. it will fail with:
**""ValueError: The field d.secondmodel.first_model was declared with a lazy reference to 'a.first_model', but app 'a' doesn't provide model 'first_model'.""**

I asume this happens because apps.get_model() inside RunPython tries to build the state of all models, which is at that point broken (as migration 3 has not run yet).

There are two fixes, none of which is nice:
1. add **dependecies** to migration in app D (not nice as we're creating false interdependency, where there truly is none)
2. add **run_before** to migration 3 and specify migration 0001 in app D (not nice as this could potentially be needed to be updated every time an app is added, otherwise the same problem could arise)

A nice solution could be to add a field such as **run_immediatelt_after** to migration 3, ensuring migration 3 is always run immediately after 2. This makes sense as those two are intimately connected and no other changes would be needed in code base from that point on."	Bug	closed	Migrations	4.2	Normal	invalid			Unreviewed	0	0	0	0	0	0
