1

I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have created a new file "script.py" inside my app.

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 somebody help me with this?

Community
  • 1
  • 1
Shivam Mitra
  • 1,040
  • 3
  • 17
  • 33

3 Answers3

18

You need is importable settings.

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

Another way call your script via the django shell:

python manage.py shell < script.py
mtt2p
  • 1,818
  • 1
  • 15
  • 22
1

As the exception says there are no apps installed ergo you have no 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 *
yorodm
  • 4,359
  • 24
  • 32
0

The following solution work from a script located in the directory where your manage.py is located:

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 Demo with your app name and put the correct database configuration for your app. This solution worked for me on Django 1.9.