Access django models from new script

I saw a lot of answers on how to use django models outside the project. But I didn’t achieve anything. I tried to implement this answer, but I am getting an error. I created a new script.py file inside my application.

script.py

from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
    DATABASE_USER = '',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = '',
    DATABASE_PORT = '',
    TIME_ZONE = 'America/New_York',
)
from models import *

When I run this script, I get an error.

Traceback (most recent call last):
  File "script.py", line 11, in <module>
    from models import *
  File "/home/shivam/study/Python/automation/project/videos/models.py", line 11, in <module>
    class video(models.Model):
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Can someone help me?

+1
source share
3 answers

You need imported settings.

import os
import django
os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
django.setup()
from .models import 

Another way to call your script through the django shell:

python manage.py shell < script.py
+8
source

As an exception, it says that applications are not installed, you do not have models yet.

from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
    # ....
    INSTALLED_APPS=["myapp","myotherapp"]

)
from myapp.models import *
+1
source

script, , manage.py:

import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

Replace the demo with your application name and put the correct database configuration for your application. This solution worked for me on Django 1.9.

0
source

Source: https://habr.com/ru/post/1663083/


All Articles