2

I have models.py and test.py files in my Django app folder.

My project is named strava, app: explorer_api

How do I import a model into 'test.py`?

I have tried:

from strava.explorer_api.models import Activity
from explorer_api.models import Activity
from .models import Activity
from models import Activity

but:

SystemError: Parent module '' not loaded, cannot perform relative import

The structure:

/
    admin.py
    apps.py
    collector.py
    models.py
    serializers.py
    test.py
    tests.py
    urls.py
    views.py
    __init__.py
migrations/
    0001_initial.py
    __init__.py
    __pycache__/
        0001_initial.cpython-35.pyc
        __init__.cpython-35.pyc
templates/
    explorer_api/
        index.html
        save.html
__pycache__/
    admin.cpython-35.pyc
    collector.cpython-35.pyc
    models.cpython-35.pyc
    serializers.cpython-35.pyc
    urls.cpython-35.pyc
    views.cpython-35.pyc
    __init__.cpython-35.pyc
Dap
  • 2,309
  • 5
  • 32
  • 44
barciewicz
  • 3,511
  • 6
  • 32
  • 72

2 Answers2

1

have a look at this Django script to access model objects without using manage.py shell if strava is your project directory then

greater than or equal to Django 1.9-1.10

import sys, os, django    
sys.path.append('full_path_to_strava_directory')
os.environ['DJANGO_SETTINGS_MODULE'] = 'strava.settings'
django.setup()

from strava.activity.models import Activity

pre Django 1.11

from strava.wsgi import application
from strava.activity models import Activity
Dap
  • 2,309
  • 5
  • 32
  • 44
  • I suggest to use `os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'strava.settings')`, so that the environment variable `DJANGO_SETTINGS_MODULE` will not be overriden if it already exists. – Tobias Ernst Nov 19 '18 at 23:43
0

Do you have explorer_api inside your INSTALLED_APPS?

Also, leave just one import in tests.py:

from explorer_api.models import Activity

Walucas
  • 2,549
  • 1
  • 21
  • 44