0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Django のプログラムを django.setup() を使って実行

Posted at

やりたいこと

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)>]
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?