Opened 21 months ago

Closed 5 months 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 Changed 21 months ago by CollinAnderson

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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 Changed 21 months ago by wim@…

  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from Uncategorized to 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 Changed 19 months ago by aaugustin

  • Component changed from Uncategorized to Database layer (models, ORM)

comment:4 Changed 5 months ago by timgraham

  • Resolution set to fixed
  • Status changed from new to closed

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