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?
1 Answer
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'>
>>>
-
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
anddjango.apps.AppConfig.get_model
? Commented Aug 18, 2017 at 15:27 -
apps.get_model
is useful in global context (models of all apps) andAppConfig.get_model
is useful for finding models for a specific app.– v1k45Commented Aug 18, 2017 at 15:31 -
@v1k45 - does this add overhead? If I
get_model('someapp.Model2
)` inside a@classmethod
ofModel1
, will I see a speed decrease? (as opposed to importing once at the top of the file in another module) I'm calling saidclassmethod
thousands of times an hour.. Commented Aug 10, 2019 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.– v1k45Commented Aug 11, 2019 at 1:57
apps.get_model()
will not help you resolve circular imports. If you avoid circular imports by usingapps.get_model()
within a function, an inline import will work just as fine. ForForeignKey
and the like, you can use string references, i.e.models.ForeignKey('myapp.MyModel')
.