Sfoglia il codice sorgente

Address model loading regression in Django 1.7

Under Django 1.7, if get_model gets called during app startup and the
models for the requested app just hasn't been loaded yet, our get_model
call fails with a LookupError.
Most of the time, it would be safe to just import the requested models,
and this is what this fix effectively does. This aligns the behaviour of
the old (pre-Django 1.7) and new get_model code again.

This is tracked as issue #1494.
master
Maik Hoepfel 10 anni fa
parent
commit
51a0859a3c
1 ha cambiato i file con 23 aggiunte e 1 eliminazioni
  1. 23
    1
      oscar/core/loading.py

+ 23
- 1
oscar/core/loading.py Vedi File

@@ -315,7 +315,29 @@ else:
315 315
         registry not being ready yet.
316 316
         Raises LookupError if model isn't found.
317 317
         """
318
-        return apps.get_registered_model(app_label, model_name)
318
+        try:
319
+            return apps.get_registered_model(app_label, model_name)
320
+        except LookupError:
321
+            # This is the fun bit. get_registered_model expectedly fails if
322
+            # it's called while the models are being loaded and the requested
323
+            # model hasn't been loaded yet.
324
+            # We try to detect that case, and then nudge the registry into
325
+            # loading the model. This should have the same effect as
326
+            # importing the correct models.py, but feels slightly less
327
+            # hackish. We're still relying on private Django APIs.
328
+            if not apps.models_ready and app_label in apps.app_configs.keys():
329
+                # We detected our corner case. Let's attempt to load the
330
+                # models. The code is taken
331
+                # from django.apps.registry.Apps.populate().
332
+                app_config = apps.app_configs[app_label]
333
+                all_models = apps.all_models[app_config.label]
334
+                app_config.import_models(all_models)
335
+                # We expect this to work now. Fingers crossed.
336
+                return apps.get_registered_model(app_label, model_name)
337
+            else:
338
+                # This must be a different case (e.g. the model really doesn't
339
+                # exist). We just re-raise the exception.
340
+                raise
319 341
 
320 342
     def is_model_registered(app_label, model_name):
321 343
         """

Loading…
Annulla
Salva