[Django]-How to Lazy Load a model in a managers to stop circular imports?

17👍

You have a few options:

1. Import by name

Django has a utility function for importing by string name so you don’t need to import yourself. There are several methods available for this (see this question: Django: Get model from string?)

from django.db.models.loading import get_model

class SomeModelManager(...):
    ...

    def some_function(self):
        model = get_model('your_app', 'YourModel')
        object = model()

2. Imports at the bottom

Add the import at the bottom of the managers.py file and make sure to simply import the module and not the models themselves.

So…

models.py:

import managers

class SomeModel(models.Model):
    ...
    objects = managers.SomeModelManager()

managers.py

class SomeModelManager(...):
    ...

    def some_function(self):
        object = models.SomeOtherModel()

import models
👤Wolph

38👍

The currently accepted answer is deprecated as of Django 1.7; from this answer, you can adapt your code like this.

from django.apps import apps

class SomeModelManager(...):
    ...

    def some_function(self):
        model = apps.get_model(app_label='your_app', model_name='YourModel')

Leave a comment