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 22462 Loading issue of models declared in tests.py due to a combination of AdminConfig, System checks, and Model._meta caching. loic84 nobody "I just had a very weird problem with my test suite, where calls to `select_related` didn't seem to work and busted every `assertNumQueries` while still returning correct values. This only happened for models defined in `tests.py` which inherited from models from another app's `models.py`. {{{ app: models.py class A(models.Model): pass admin.py @admin.register(A) class AAdmin(admin.ModelAdmin): list_filters = 'id', app2: tests.py class B(A): pass }}} The problem turned out to be that the various caches in `A._meta` were wrong (those used by `get_field_by_name()` and friends). Calls to `select_related('b')` were silently ignored (because that's what `select_related` do for non-existing relations) but calls to `filter(b=something)` would have failed with a `FieldError ` despite `A` having the `A.b` descriptor. Here is how the cache got to hold the wrong values: - `Apps.populate()` calls `AdminConfig.ready()`. - `AdminConfig.ready()` calls `autodiscover()`. - `autodiscover()` causes `AAdmin` to register, which in turn triggers `ModelAdmin.check()`. - `ModelAdmin.check()` inspects the model fields and fills up the caches in `_meta` by doing so. - `app2.tests.B` is loaded but it's already too late." Bug closed Core (Other) dev Normal duplicate Accepted 0 0 0 0 0 0