22
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ローカルのPythonスクリプトからDjangoを使う

Last updated at Posted at 2017-04-15

色々Webに転がってる情報試したらちょっと苦労したのでメモ
以下Django1.10, python3.6.0で動作確認

local.py
import sys
import os
import django

sys.path.append('/Path/to/your/project')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rootdir.settings')  # 自分のsettings.py


def call():
    django.setup()
    from yourapp.models import YourModel

    objects = YourModel.objects.all()
    for obj in objects:
        print(obj)


if __name__ == '__main__':
    call()

django.setup()

from yourapp.models import YourModel
より先に実行しないと、

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
と、言われる。

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rootdir.settings')
↑この設定絡みで↓のような事言われた気がしたけど詳細は忘れた。

django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.


sys.path.appendの中身まではPycharmさんは見に行ってくれないので
Preferences->Project:yourproject->Project Structureの画面の右端にある
Add Content Rootで当該プロジェクトを指定。

22
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?