Django analysis-how to customize manage commands, django custom manage
We have used Django manage. py command, while manage. py is a command line tool automatically generated in the root directory when we create a Django project. It can execute some simple commands. Its function is to put the Django project in sys. in the path directory, set the DJANGO_SETTINGS_MODULE environment variable to the setting of the current project. py file. Let's take a look at the Code:
#!/usr/bin/env pythonimport osimport sysif __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SNCRM.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Here, the script will execute the corresponding results based on the commands passed in the execute_from_command_line () method. That is to say, we can write commands that can be recognized by this function, so that we can expand the manage. py function to a large extent.
How can we write such a custom manage command?
First, create a module named management under the apps module so that Django can automatically discover our commands, in this way, we can create the commands we need in our new management module. Of course, not all py file systems will recognize them as commands, only those that reference BaseCommand can be correctly identified, and our command class must inherit from BaseCommand. The following code is used for Demonstration:
#django command importfrom django.core.management.base import BaseCommandclass Command(BaseCommand): def handle(self, *args, **options): print 'hello, World !'
This is the most basic command. When using this command, you only need to enter the command file name after manage. py.
Of course, the above example is the simplest. This function is generally used only when the project is initialized. Therefore, our scripts are generally used for database operations, this feature is especially important when our project uses a third-party ORM framework, because the Django syncdb command Cannot initialize a third-party ORM, only the built-in ORM of Django can be initialized. Therefore, this function is often used when I use other ORM such as SQLAlchemy. It is recorded here.