django manage.py 扩展

在django中会常常敲python manage.py runserver 这个命令,其中manage.py 这个文件会常常用到,本次写一下manage.py 怎么扩展,以扩展初始化数据库表host为例html

如一个Host model python

class Host(model.Model):
     属性:id, ip, hostname。。。等

一种状况是每次运行都须要初始化数据库,以后手动去添加数据到数据库中,感受很麻烦,有没有一个命令敲一下就能够了呢,查了资料发现是有的数据库

参考帮助文档:custom-management-commands.html(django 文档下载的html页面)django

或者: https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/app

在app 下面新建目录management/commands 在commands文件夹下面写 python 类 ,须要继承 BaseCommand 将上面连接中的 内容修改一下命令行

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    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']:
            print ("args=", args)
            self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

cmd 命令行中执行code

python manage.py test 1

相关文章
相关标签/搜索