How do I correctly import models in Python if I'm having such directories?
Question:
I’m using Django-REST framework with a telegram-bot in here. I need to import models
from Django inside my telegram-bot file. I’m getting module not found error and probably thinking something wrong. Telegram-bot file is commands.py and the django models is models.py. The whole project looks like this:
I just want to properly import models
inside my commands.py file
Answers:
Here is the possible solution for your question..
add following code inside my commands.py file
import sys
from django.apps import apps
from django.conf import settings
settings.configure(INSTALLED_APPS=['app_name'])
apps.populate(settings.INSTALLED_APPS)
from app_name.models import YourModel
also you may need to update path.
import sys
sys.path.append('path/to/your/django/project')
As you mentioned, You are using Django REST Framework, so you should try with a serializer file. import your model in serializer file, because the syntax is correct ‘from app_name.models import YourModel’. Moreover, instead of settings.configure(INSTALLED_APPS=[‘app_name’]) try this in settings.py
file in INSTALLED_APPS = ‘app_name.apps.AppNameConfig’.
I’m using Django-REST framework with a telegram-bot in here. I need to import models
from Django inside my telegram-bot file. I’m getting module not found error and probably thinking something wrong. Telegram-bot file is commands.py and the django models is models.py. The whole project looks like this:
I just want to properly import models
inside my commands.py file
Here is the possible solution for your question..
add following code inside my commands.py file
import sys
from django.apps import apps
from django.conf import settings
settings.configure(INSTALLED_APPS=['app_name'])
apps.populate(settings.INSTALLED_APPS)
from app_name.models import YourModel
also you may need to update path.
import sys
sys.path.append('path/to/your/django/project')
As you mentioned, You are using Django REST Framework, so you should try with a serializer file. import your model in serializer file, because the syntax is correct ‘from app_name.models import YourModel’. Moreover, instead of settings.configure(INSTALLED_APPS=[‘app_name’]) try this in settings.py
file in INSTALLED_APPS = ‘app_name.apps.AppNameConfig’.