Loading issue of models declared in tests.py due to a combination of AdminConfig, System checks, and Model._meta caching.
|Reported by:||loic84||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
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.
Change History (15)
comment:1 Changed 15 months ago by charettes
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted