Opened 11 years ago
Closed 10 years ago
#20839 closed Cleanup/optimization (fixed)
models.py module is imported multiple times.
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.5 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When a models.py module raises an ImportError for whatever reason, Django will attempt to import it many times. This can be demonstrated thus:
# models.py print 'loaded' import nonexistent_module
'loaded' will be printed more than once. This is due to the 'postponing' behavior during model loading: https://github.com/django/django/blob/master/django/db/models/loading.py#L118.
This is an issue for me because I have a registry system that tracks models and only allows them to be registered once.
class WhateverModel(models.Model): pass registry.register(WhateverModel) # checks that models are only registered once import nonexistent_module # oops, now it's registered twice (or more)
Change History (4)
comment:1 by , 11 years ago
comment:2 by , 11 years ago
Triage Stage: | Unreviewed → Accepted |
---|---|
Type: | Uncategorized → Cleanup/optimization |
Accepted, because it is weird that things are imported more than once. I'm not sure whether this is easy to solve though. Maybe the app loading refactor will solve this problem whenever it lands.
comment:3 by , 11 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|
comment:4 by , 10 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
Using the code to reproduce and runserver, I saw "loaded" printed twice up until 966de8497373dc47756105516b4b839734ed316e, so I think this is fixed.
Not sure if this helps, but Django is aware that models.py files often get loaded multiple times, and has its own workaround to ignore multiple registration attempts.
https://github.com/django/django/blob/master/django/db/models/base.py#L258