![見出し画像](https://assets.st-note.com/production/uploads/images/133200972/rectangle_large_type_2_174ff48970787c37b433bc8c428cf42d.png?width=800)
Creating Custom Commands in Django
As a note, I will summarize below the method for creating your own custom commands in Django.
Create app_name/management/commands Directory
create management directory and create __init__py file and commands directory in it.
![](https://assets.st-note.com/img/1709803733697-zW8YHGHMrp.png)
Create Custom Command file in commands directory
Create original command in commands directory.
![](https://assets.st-note.com/img/1709803918182-wZ2h4wRufd.png)
My custom command
# DropAllTables.py
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Drop all tables command"
def handle(self, *args, **options):
cursor = connection.cursor()
cursor.execute("DROP SCHEMA public CASCADE;")
cursor.execute("CREATE SCHEMA public;")
cursor.execute("GRANT ALL ON SCHEMA public TO user_name;")
You can use command like this.
$ python manage.py DropAllTables
It's also possible to accept arguments.
You can accept command line arguments like this.
# DropSpecificTable.py
class Command(BaseCommand):
help = "Delete specific table"
def handle(self, *args, **options):
table_name = options['table_name']
cursor = connection.cursor()
cursor.execute("DROP table " + table_name + ";")
$ python manage.py DropSpecificTable --table_name=specific_table_name
この記事が気に入ったらサポートをしてみませんか?