django BaseCommand
使用命令行 执行脚本
from django.core.management.base import BaseCommand
from django.db import transaction
from apps.db.models import AdminMenu
class Command(BaseCommand):
help = '管理端、PC端、H5端菜单'
def add_arguments(self, parser):
parser.add_argument('-func', action='store', dest='func', default=False, help='')
parser.add_argument('-arg', action='store', dest='arg', default='', help='')
def handle(self, *args, **options):
# print(args, options)
# print('====禁止执行====')
# return
_func = options.get('func', None) # 操作方法
arg = options.get('arg', None) # 操作参数
if hasattr(self, _func):
if arg:
eval('self.%s(%s)' % (_func, arg))
else:
eval('self.%s()' % _func)
else:
print('error: 无效的参数func')
print('===========end==============')
def pc(self):
menus = [
{"name": "主页",
"code": "",
"sort": 1,
"icon": "/statics/icon/admin/menu1.svg",
"is_menu": True,
"type": 2,
"subs": []
},
]
with transaction.atomic():
for menu in menus:
obj1 = AdminMenu.objects.create(
name=menu['name'],
code=menu['code'],
sort=menu['sort'],
icon=menu['icon'],
is_menu=menu['is_menu'],
type=menu['type'],
enabled=True,
pid=None,
pids=None
)
self.sub_menu(obj1, menu['subs'], [obj1.uuid])
def sub_menu(self, obj1, subs, pids):
if subs:
for sub in subs:
obj2 = AdminMenu.objects.create(
name=sub['name'],
code=sub['code'],
sort=sub['sort'],
icon=sub['icon'],
is_menu=sub['is_menu'],
type=sub['type'],
enabled=True,
pid=obj1,
pids=pids
)
sub_pids = pids + [obj2.uuid]
self.sub_menu(obj2, sub['subs'], sub_pids)
用法
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17876759.html