やりたいこと
Django のプログラムをカスタムコマンドを作成せずに、簡易に検証したい。
環境変数の DJANGO_SETTINGS_MODULE に "{アプリケーション名}.settings" を指定して django.setup() を実行することで、Django アプリケーションのプログラムを実行することができるようになる。
動作検証
プログラム構成
db_test1 # ルートディレクトリ
├── db_test1 # プロジェクトディレクトリ
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py # 設定ファイル
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── test # 動作検証用プログラムのディレクトリ
│ └── test_db.py # 動作検証用プログラム
└── test1 # アプリケーション
├── __init__.py
├── admin.py
├── management
├── migrations
├── models.py
└── views.py
プログラム例
test/test_db.py
import os
import django
from django.db.models import OuterRef, Subquery
from tenant_schemas.utils import schema_context
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)) + '/\
../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'db_test1.settings')
django.setup()
from test1.models import Item, AttrValue
def test_items(schema):
with schema_context(schema):
items = (
Item.objects.all()
)
print(list(items))
def test_attr_values(schema):
with schema_context(schema):
attr_values = (
AttrValue.objects.all()
)
print(list(attr_values))
def main():
schema = 'public'
test_items(schema)
test_attr_values(schema)
return 0
if __name__ == '__main__':
res = main()
exit(res)
プログラム実行
コマンド
python test/test_db.py
実行結果
[<Item: item_01>, <Item: item_01>, <Item: item_01>, <Item: item_02>]
[<AttrValue: item_01: (length, 10)>, <AttrValue: item_01: (weight, 20)>, <AttrValue: item_01: (length, 10)>, <AttrValue: item_01: (weight, 20)>, <AttrValue: item_02: (length, 15)>, <AttrValue: item_02: (weight, 25)>]