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?
What is the equivalent of django.db.models.loading.get_model() in Django 1.9?
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
and django.apps.AppConfig.get_model
? –
Blowing 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. –
Nasopharynx @Nasopharynx - 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.. –
Lorikeet @Lorikeet 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. –
Nasopharynx © 2022 - 2024 — McMap. All rights reserved.
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')
. – Bornstein