4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django のカスタムコマンドの作り方

Last updated at Posted at 2018-12-16

カスタムコマンドの作り方です。
次のページを参考にしました。
How to Create Custom Django Management Commands

次のようにユーザーがある状況で カスタムコマンドでユーザー一覧を表示してみます。
users_dec15.png

プロジェクト proj01
アプリ home
とします。

1)まず、コマンドを入れるフォルダーを用意します。

mkdir home/management
mkdir home/management/commands
  1. 時刻を表示するコマンドを作成してみます。
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
  1. ユーザー一覧のコマンドを作成します。
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
4
8
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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?