Django管理员命令带/不带参数

1 投票
1 回答
1936 浏览
提问于 2025-04-17 17:05

有没有可能在同一个管理命令的类里,既可以选择带参数运行,也可以选择不带参数运行呢?

比如说,可以判断如果参数是空的,就执行这个命令;否则就执行那个命令?

提前谢谢你。

1 个回答

3

当然,可以这样做,只需检查传递给处理方法的'args',像这样:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'prints no args if there are no args'

    def handle(self, *args, **options):
        if len(args) == 0:
            print 'no args'
        else:
            for pkid in args:
                print pkid

撰写回答