Use django model from interpreter

When I try to access django's model directly from the interpreter, I get angry with the following error:

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.

To prevent this, it seems that you need to call the following before importing the model. Calling it later will result in an error.

django.setup()

In addition, you need to set environment variables

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

The summary is as follows.

>>> 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 []>

Recommended Posts

Use django model from interpreter
Use fastText trained model from Python
DJango Memo: From the beginning (model settings)
Django model: ManyToManyField
Use Django from a local Python script
Use thingsspeak from python
Use fluentd from python
Use Gentelella with django
Use MySQL from Python
Django memo # 1 from scratch
High Performance Django --Model
Use MySQL from Python
Use LESS with Django
Use BigQuery from python.
Use MySQL with Django
Use mecab-ipadic-neologd from python
How to use Keras ~ From simple model generation to CNN ~
How to use Azure Table storage from Django (PTVS)
Use Django features from batch scripts outside your Django project
[Django] Give Form a dynamic initial value from Model
Django starting from scratch (part: 2)
Django starting from scratch (part: 1)
Use MySQL from Anaconda (python)
The story of a Django model field disappearing from a class
Template registration from Django Bootstrap
Use prefetch_related conveniently with Django
Use e-Stat API from Python
Use AWS interpreter with Pycharm
Use MLflow with Databricks ④ --Call model -
Use httpie from windows git bash
Use Stanford Core NLP from Python
Load Django modules with an interpreter
How to use SWIG from waf
Django: Import a class from a string
DJango Memo: From the beginning (preparation)
Create new application use python, django
Read and use Python files from Python
Forcibly use Google Translate from python
Try sklearn's regression model from scratch
Automatically generate model relationships with Django
Use kabu Station® API from Python
[Beginner] Get from Django Query database
Use Azure Blob Storage from Python
Use the Flickr API from Python
Get the value from the [Django] Form
[Django] Use MessagePack with Django REST framework
Use Cloud Datastore from Compute Engine
Use Google Analytics API from Python
Use Unicode 6.0 emoji with django / MySQL
Deploy Python face recognition model on Heroku and use it from Flutter ②
Deploy Python face recognition model on Heroku and use it from Flutter ①