I want to use get_model()
to avoid cyclic imports in my models, but I get name 'get_model' is not defined
error. I read that get_model()
was depreciated in 1.8 and apparently is not present in 1.9. What is the equivalent call? Or is there another way to avoid cyclic imports in two models.py
files?
Asked
Active
Viewed 2.3k times
39

Zygro
- 6,849
- 11
- 28
- 43
-
3`apps.get_model()` will not help you resolve circular imports. If you avoid circular imports by using `apps.get_model()` within a function, an inline import will work just as fine. For `ForeignKey` and the like, you can use string references, i.e. `models.ForeignKey('myapp.MyModel')`. – knbk Mar 26 '16 at 12:42
1 Answers
84
django.db.models.loading.get_model()
has been removed in django 1.9.
You are supposed to use django.apps
instead.
>>> from django.apps import apps
>>> apps.get_model('shop', 'Product')
<class 'shop.models.Product'>
>>>

Boris Verkhovskiy
- 14,854
- 11
- 100
- 103

v1k45
- 8,070
- 2
- 30
- 38
-
This was really helpful in my converting an app to go from Django 1.8 to Django 1.11 compatibility. What is the difference between `django.apps.apps.get_model` and `django.apps.AppConfig.get_model`? – MadPhysicist Aug 18 '17 at 15:27
-
`apps.get_model` is useful in global context (models of all apps) and `AppConfig.get_model` is useful for finding models for a specific app. – v1k45 Aug 18 '17 at 15:31
-
@v1k45 - does this add overhead? If I `get_model('someapp.Model2`)` inside a `@classmethod` of `Model1`, will I see a speed decrease? (as opposed to importing once at the top of the file in another module) I'm calling said `classmethod` thousands of times an hour.. – zerohedge Aug 10 '19 at 21:15
-
1@zerohedge The `get_model` method imports a python class using string, similar things are done throughout django. You won't see a speed issue due to this. Even if you called it few hundred thousand times a second. PS: If you can import the model, you should do that instead. `get_model` is intended to be used for dynamically importing or lazyloading models. – v1k45 Aug 11 '19 at 01:57