简体   繁体   中英

Django: Getting models with apps.get_model on models.py

On circular import of Django Is their any way i can grab a model object with myModel = apps.get_model('app_name', 'model_name') inside models.py file ?

I know i can use models.ForeignKey('app.model',....)

But in my case i am making a query in the models.py for custom function. So that i need to grab the model object. Also can't import it in normal way as already imported this file class in the other file. So must be a circular import.

This code myModel = apps.get_model('app_name', 'model_name') works fine on views.py but in models.py doesn't. Since according to django the all models.py get called after settings.py and after that views and others. so while trying to use get_model inside models.py getting this error

File "/home/mypc/.virtualenvs/VSkillza/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Thanks in advance :)

You can break the circular import by moving the import inside the custom function. That way, the model is loaded when the function runs, not when the module is loaded.

def my_function():
    from myapp.models import MyModel

The circular import suggests that your code is structured incorrectly, but we can't give you any suggestions since you haven't shown it.

You can try this.

     import importlib

     mymodels = importlib.import_module("app.models")
     mymodels.YourModel
     #query
     mymodels.YourModel.objects.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM