| 6 | |
| 7 | Also, there's only a few failures when adding assertions for `_meta.apps` coherency once they are appropriately repointed in `StateApps.clone` like they should |
| 8 | |
| 9 | {{{#!diff |
| 10 | diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py |
| 11 | index 9b62edad1f..970197cae7 100644 |
| 12 | --- a/django/db/migrations/state.py |
| 13 | +++ b/django/db/migrations/state.py |
| 14 | @@ -322,6 +322,9 @@ class StateApps(Apps): |
| 15 | clone.all_models = copy.deepcopy(self.all_models) |
| 16 | clone.app_configs = copy.deepcopy(self.app_configs) |
| 17 | # Set the pointer to the correct app registry. |
| 18 | + for _, models in clone.all_models.items(): |
| 19 | + for model in models.values(): |
| 20 | + model._meta.apps = clone |
| 21 | for app_config in clone.app_configs.values(): |
| 22 | app_config.apps = clone |
| 23 | # No need to actually clone them, they'll never change |
| 24 | diff --git a/django/db/models/options.py b/django/db/models/options.py |
| 25 | index 078b831b76..2183813a93 100644 |
| 26 | --- a/django/db/models/options.py |
| 27 | +++ b/django/db/models/options.py |
| 28 | @@ -704,7 +704,8 @@ class Options: |
| 29 | ) |
| 30 | for f in fields_with_relations: |
| 31 | if not isinstance(f.remote_field.model, str): |
| 32 | - related_objects_graph[str(f.remote_field.model._meta.concrete_model._meta)].append(f) |
| 33 | + assert f.remote_field.model._meta.concrete_model._meta.apps is self.apps |
| 34 | + related_objects_graph[f.remote_field.model._meta.concrete_model._meta].append(f) |
| 35 | |
| 36 | for model in all_models: |
| 37 | # Set the relation_tree using the internal __dict__. In this way |
| 38 | @@ -712,7 +713,8 @@ class Options: |
| 39 | # __dict__ takes precedence over a data descriptor (such as |
| 40 | # @cached_property). This means that the _meta._relation_tree is |
| 41 | # only called if related_objects is not in __dict__. |
| 42 | - related_objects = related_objects_graph[str(model._meta.concrete_model._meta)] |
| 43 | + assert model._meta.concrete_model._meta.apps is self.apps |
| 44 | + related_objects = related_objects_graph[model._meta.concrete_model._meta] |
| 45 | model._meta.__dict__['_relation_tree'] = related_objects |
| 46 | # It seems it is possible that self is not in all_models, so guard |
| 47 | # against that with default for get(). |
| 48 | }}} |