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?

More than 3 years have passed since last update.

Djangoでカスタムコマンドを作る

Posted at

概要

Djangoでカスタムコマンドを作成して実行してみる

カスタムコマンドの環境を作成する

  1. アプリケーションのディレクトリにmanagementフォルダを作成
  2. managementフォルダにcommandsフォルダを作成
  3. 好きなコマンド名を考える
  4. commandsフォルダに好きなコマンド名.pyファイルを作成

コマンドを実行される処理を記述

好きなコマンド名.pyファイルの中身

management/commands/好きなコマンド名.py
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('カスタムコマンドを実行したよ'))

動作確認

$ python manage.py 好きなコマンド名
カスタムコマンドを実行したよ

こんな感じで簡単にカスタムコマンドを作成できます。
動作確認やcronと合わせて定期的に処理を実行させるなど使えると思います。

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?