カスタム shell コマンドの作り方¶
Djangoの shell は、モデルと設定へのアクセスを提供する対話型の Python 環境であり、コードのテスト、クエリの実験、アプリケーションデータとのやりとりに役立ちます。
shell コマンドをカスタマイズすることで、機能を追加したり、特定のモジュールをプリロードしたりできます。そのためには、 django.core.management.commands.shell.Command のサブクラスを作成し、既存の shell 管理コマンドをオーバーライドする新しい管理コマンドを作成します。詳細については、 コマンドのオーバーライド に関するガイドを参照してください。
自動インポートをカスタマイズする¶
shell 管理コマンドの自動インポート動作をカスタマイズするには、 get_auto_imports() メソッドをオーバーライドします。このメソッドは、アプリケーションで利用可能なオブジェクトまたはモジュールのインポートパスのシーケンスを返す必要があります。例えば:
polls/management/commands/shell.py¶from django.core.management.commands import shell
class Command(shell.Command):
def get_auto_imports(self):
return super().get_auto_imports() + [
"django.urls.reverse",
"django.urls.resolve",
]
The customization above adds resolve() and
reverse() to the default namespace, which already includes
all models from the apps listed in INSTALLED_APPS plus what is
imported by default. These objects will be available in the shell without
requiring a manual import.
このようにカスタムした shell コマンドを verbosity=2 を付けて実行すると、次のように表示されます:
13 objects imported automatically:
from django.db import connection, reset_queries, models
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.contrib.auth.models import Group, Permission, User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.models import Session
from django.urls import resolve, reverse
from django.utils import timezone
Automatic imports of common utilities, such as django.conf.settings,
were added.
オーバーライドされた shell コマンドにインポートできないパスが含まれている場合、 verbosity を 1 以上に設定するとエラーが表示されます。重複したインポートは自動的に処理されます。
特定の shell セッションで自動インポートを無効にしたい場合は、 --no-imports フラグを使用してください。自動インポートを恒久的に無効にするには、get_auto_imports() をオーバーライドして None を返すようにします:
class Command(shell.Command):
def get_auto_imports(self):
return None