chrise
chrise

Reputation: 4253

Django Apps aren't loaded yet: How to import models

I have a Django project looking like

> project
    > gui
        > __init__.py
        > models.py
        > views.py
        > ...
    > project
        __init__.py
        ...

I am trying to sync the sqllite db in django with some info I periodically query from other sources. So in project.init.py I spawn a thread that periodically queries data. However, I am having trouble accessing my models from there and update the database, because when I try to import them into init.py

from gui.models import GuiModel

I get

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Is there a trick to do that or a different way to create a separate thread?

Upvotes: 0

Views: 453

Answers (2)

vorujack
vorujack

Reputation: 1950

If you send all details correctly, I think you have a circular import in your code. simple way is to to move import into your function.

also you can create a custom command in your project and add a cronjob to your server to do this works.

Upvotes: 1

JPG
JPG

Reputation: 88549

From the Django Official Doc, If you’re using components of Django “standalone” you should follow something like this,

import sys
import os
import django

sys.path.append("/path/to/project")  # here project is root folder(means parent).
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
django.setup()

from gui.models import GuiModel

# do something here with models

Upvotes: 1

Related Questions