Applications can register their own actions with manage.py. For example, you might want to add a manage.py action for a Django app that you’re distributing. In this document, we will be building a custom closepoll command for the polls application from the tutorial.
To do this, add a management/commands directory to the application. Django will register a manage.py command for each Python module in that directory whose name doesn’t begin with an underscore
manage.py 会将不是下划线开头的注册成命令
目录结构如下
- 自定义命令行如下
from django.core.management.base import BaseCommand
from django.utils.crypto import get_random_string
class Command(BaseCommand):
help = '命令描述'
# 参数设定
def add_arguments(self , parser):
parser.add_argument('-u', dest='user', nargs="+", type=str)
parser.add_argument('--username', dest='user', nargs="+", type=str)
def handle(self, *args, **kwargs):
username = kwargs['kwargs']
#这里处理你的逻辑
- 运行命令
python manage.py myapp_task -u user1 user2