25

In Django you can create managers for your models. I do this by added a new file called managers.py and in my model objects = MyManager().

To stop circular imports I do self.model. However, if I need to reference a different model in my manager i.e.

from models import SecondModel
second= SecondModel(name=test).save()
self.model(second=second)

I get the following error: ImportError: cannot import name SecondModel

So is there a way in Django to lazy load a model?

Prometheus
  • 32,405
  • 54
  • 166
  • 302

2 Answers2

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')
Community
  • 1
  • 1
Saturnix
  • 10,130
  • 17
  • 64
  • 120
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
Community
  • 1
  • 1
Wolph
  • 78,177
  • 11
  • 137
  • 148