Opened 11 years ago

Closed 9 years ago

#20839 closed Cleanup/optimization (fixed)

models.py module is imported multiple times.

Reported by: gwahl@… 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 Collin Anderson, 11 years ago

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

comment:2 by wim@…, 11 years ago

Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/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 Aymeric Augustin, 11 years ago

Component: UncategorizedDatabase layer (models, ORM)

comment:4 by Tim Graham, 9 years ago

Resolution: fixed
Status: newclosed

Using the code to reproduce and runserver, I saw "loaded" printed twice up until 966de8497373dc47756105516b4b839734ed316e, so I think this is fixed.

Note: See TracTickets for help on using tickets.
Back to Top