Needless to say to Django experts, Django makes it easy to create custom commands!
$ python manage.py hoge
It is in the form of. The parts like runserver
, migrate
, and make migrations
.
This time I implemented it because I wanted to add a parameter after hoge
, so share it with a memo
image
$ python manage.py hoge 1 2
$ django-admin.py startapp app
I will implement it on the assumption that I have created an app named ʻapp`.
app/
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
I think that it has a structure like that. If not changed
$ mkdir -p app/management/commands
$ cd app/management/commands
$ touch __init__.py
$ touch plus.py #Any name "plus" will be the custom command name
hoge.py
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
args = '<param_1 param_2 ...>'
help = 'A command to display the total of parameters'
def add_arguments(self, parser):
parser.add_argument('parameters', nargs='+', type=int)
def handle(self, *args, **options):
print(sum(options['parameters']))
The above is an appropriate one for the time being, so it is a command that just adds parameters and displays it.
$ python manage.py plus 1 2 3 4
10
It should look like this!
Recommended Posts