Posts /

Django Custom Command 만들기

05 Jul 2018

개요

참고

과정

모듈

from django.core.management.base import BaseCommand, CommandError
from polls.models import Question as Poll


class Command(BaseCommand):

    # python manage.py closepoll [-h | --help] 에 의해 출력될 문자열
    # 명령어에 대한 간단한 설명이 들어가면 된다.
    help = 'Closes the specified poll for voting'

    # 명령어에 받을 인자를 정의함
    def add_arguments(self, parser):
        parser.add_argument('poll_id', nargs='+', type=int)

    # 실제 처리부분
    def handle(self, *args, **options):
        for poll_id in options['poll_id']:
            try:
                poll = Poll.objects.get(pk=poll_id)
            except Poll.DoesNotExist:
                raise CommandError('Poll "%s" does not exist' % poll_id)

            poll.opened = False
            poll.save()

            self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
$ python manage.py closepoll 5  -> OK
$ python manage.py closepoll 5 22
...
error: unrecognized arguments: 22

Twitter Facebook Google+