[PYTHON] Dive into the Django Custom command [1]


This is the first article posted. I decided to start wanting to leave what I learned in a memorable way.

Recently, I am studying with the motto of mastering django deeply. This article is a footstep in learning about django's custom commands.

table of contents

  1. What is a django custom command?
  2. Preparation for using custom commands
  3. How to create a custom command
  4. Custom command flow
  5. Customize custom commands
  6. Summary

1. What is a django custom command?

It is a mechanism that can execute python scripts with CUI,

・ Various functions of django (db ORM etc.) can be used ・ Easy command management

There are advantages such as. The latter is

-List available commands-

python manage.py --help

-Show custom command description-

python manage.py customcommand --help
usage: manage.py customcommand2 [-h] [--version] [-v {0,1,2,3}]
                                [--settings SETTINGS]
                                [--pythonpath PYTHONPATH] [--traceback]
                                [--no-color] [--force-color] [--skip-checks]

Function to store data

This is possible.

2. Preparation for using custom commands

(1) Create an application (this time created with the name script)

python manage.py startapp script

(2) Create a hierarchical structure of management / commands

  ├── management/
         ├── commands/
  ├── admin.py
  ├── apps.py
  ├── models.py
  ├── tests.py
  └── views.py

(3) Put the script file under commands Here, create it with the name customcommand.py

3. How to create a custom command

When I read the comment of the baseBaseCommand class, it says, "If you don't want to change the command execution flow, you can use a child class named Command that inherits the BaseCommand class." I think that the following configuration is okay.


class Command(BaseCommand):

    #Describe the content you want to process in the script in the overridden handle function
    def handle(self, *args, **options):

4. Custom command flow

This is a story about how the custom command of the main subject is called and what kind of function is used for processing.

The processing flow is as follows.

  1. Execute python manage.py customcommand

  2. Call the Command class

  3. run_from_argv method

  4. create_parser method

  5. add_arguments method

  6. parse_args method

  7. execute method

  8. handle method

I got the image that a function called run_from_argv shows the overall processing flow and performs detailed processing in other functions. Therefore, the concept of detailed processing after 4 is described below.

4. create_parser method

Arguments are in the form of [command line argument [0], command line argument [1]] -> In this example, ['manage.py','customcommand']

First, cut out the file name of manage.py. -> If manage.py is described with the full path, only manage.py will be retrieved here.

Next, create a Parser object. The Parser object has the following attributes. -prog: "manage.py customcommand" (instructions separated by spaces) -description: help statement (obtained by self.help) -formatter_class: (predetermined Django help option such as --version) Such

5. add_arguments method

Add the argument you want to use in the process to the parser object. For example

parser.add_argument('parameters', nargs='+', type=int)

 Then you can force one or more arguments of type int.
 -> ``` Python manage.py customcommand 3 5``` etc.

### 6. parse_args method
 Here, check the format of the instruction group actually entered.
 -If Django's help option such as --version comes, end the process here
 -If the input format is different, the expected argument (contents of parser) is output as standard.

### 7,8. execute method, handle method
 It is passed to the execute method and passed to the handle method only when the format check is passed in the process of 6.
 * If an argument is added in the process of 5, it can be referred from the options argument of the handle method.

# 5. Customize custom commands
### Add command help statement

help = 'Function to'

OK if you define the help argument

Add argument

A brief summary of how to use ArgumentParser It was explained in detail in this article.

6. Summary

I searched a lot, but I got the impression that it would be okay if I put down the handle function, add_arguments function, and the addition of help. As for the concept of parse object, it seems to be widely used for handling variable arguments, so I learned it.

Recommended Posts

Dive into the Django Custom command [1]
Create custom Django commands and run them from the command line
Django + Docker command
Put the file uploaded by django into MinIO
About the service command
[Django] Change the Default IP address of the runserver command
Install the pip command
[Django] Rename the project
Django command completion settings
How to write custom validations in the Django REST Framework
Paver Application-Incorporate into the project
Clone using the dd command
Speed up the netstat command
Until the shell finds the command
[Learning memo] Django command summary
[Note] [For myself] Django command