LoginSignup
1
0

More than 3 years have passed since last update.

djangoのmodelをインタプリタから使う

Last updated at Posted at 2020-09-10

インタプリタから直でdjangoのモデルにアクセスしようとすると以下のエラーで怒られる。

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.setup()

加えて、環境変数を設定する必要がある

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings')
'app_name.settings'

まとめると以下のようになる。

>>> import django
>>> import os
>>> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings')
'app_name.settings'
>>> django.setup()
>>> from APP_NAME.models import YourModel
>>> YourModel.objects.all()
<QuerySet []>
1
0
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
1
0