Search code examples
djangomodel

How to access a Django model outside a Django project?


The problem below is raised after reviewing all the related SO questions, but unfortunately none of the answers brought a solution in my case (similar problem like: How to access Django models outside of Django?).

(with Django version: 4.1.1)

Having an application "simo" available with the related model, the db access works well from Django shell; but trying to access to it from outside Django as "scheduling.py", it just does not work.

    import os
    import django
        
    os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
    django.setup()
        
    from django.db import models
    from simo.models import Tasks

I tried to execute my python script in any folder:

  • beside manage.py,
  • beside settings.py and
  • beside models.py but none of them works.
[mysite]
    [mysite]
        [simo]
            [migrations]
            views.py
            models.py
            urls.py
            __init__.py
            apps.py
            tests.py
            admin.py
        settings.py
        urls.py
        __init__.py
        wsgi.py
        asgi.py
    scheduling.py
    __init__.py
    db.sqlite3
    manage.py

The error received is:

C:\...\python.exe C:/.../mysite/scheduling.py
Traceback (most recent call last):
  File "C:\...\mysite\scheduling.py", line 5, in <module>
    django.setup()
  File "C:\...\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\...\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\...\lib\site-packages\django\apps\config.py", line 178, in create
    mod = import_module(mod_path)
  File "C:\...\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'simo'

Process finished with exit code 1

Could anyone advise me on how to resolve this issue?


Solution

  • Try calling

    from django.db import models and from simo.models import Tasks before django.setup()