カスタムコマンドの作り方です。
次のページを参考にしました。
How to Create Custom Django Management Commands
次のようにユーザーがある状況で カスタムコマンドでユーザー一覧を表示してみます。
プロジェクト proj01
アプリ home
とします。
1)まず、コマンドを入れるフォルダーを用意します。
mkdir home/management
mkdir home/management/commands
- 時刻を表示するコマンドを作成してみます。
home/management/commands/what_time_is_it.py
from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = 'Displays current time'
def handle(self, *args, **kwargs):
time = timezone.now().strftime('%X')
self.stdout.write("It's now %s" % time)
実行します。
python manage.py what_time_is_it
実行結果
$ python manage.py what_time_is_it
It's now 11:53:25
- ユーザー一覧のコマンドを作成します。
home/management/commands/list_users.py
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
class Command(BaseCommand):
def handle(self, *args, **kwargs):
for user in User.objects.all():
print(user.id,"\t", end="")
print(user.username,"\t", end="")
print(user.email)
実行します。
python manage.py list_users
実行結果
$ python manage.py list_users
1 admin test@test.com
2 test01
3 test02
4 test03