|
@@ -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
|
"""
|