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
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')
- [Django]-How to get getting base_url in django template
- [Django]-What is a "django backend"?
- [Django]-Django model default sort order using related table field
Source:stackexchange.com