40

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
  • 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
    Commented Mar 26, 2016 at 12:42

1 Answer 1

85

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'>
>>> 

Django docs reference

4
  • 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? Commented Aug 18, 2017 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
    Commented Aug 18, 2017 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
    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.
    – v1k45
    Commented Aug 11, 2019 at 1:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.