Django 管理命令看不到参数?

Django management command cannot see arguments?

自从升级到 Django 1.8 后,我的 Django 管理命令中出现了一个奇怪的错误。

我运行它如下:

python manage.py my_command $DB_NAME $DB_USER $DB_PASS

然后我收集参数如下:

class Command(BaseCommand):

def handle(self, *args, **options):
    print args
    db_name = args[0]
    db_user = args[1]
    db_pass = args[2]
    self.conn = psycopg2.connect(database=db_name, user=db_user,
                                 password=db_pass)

以前这工作正常,但现在我看到这个错误:

usage: manage.py my_command [-h] [--version] [-v {0,1,2,3}]
                                             [--settings SETTINGS]
                                             [--pythonpath PYTHONPATH]
                                             [--traceback] [--no-color]
manage.py my_command: error: unrecognized arguments: test test test

它甚至没有达到 print args 声明的程度。

如果我 运行 它没有任何参数,那么它会在 args[0] 行出错,这不足为奇。

我在这里使用 args 是不是错了?还是有其他事情发生?

这是 Django 1.8 中的一个变化。详尽here:

Management commands that only accept positional arguments¶

If you have written a custom management command that only accepts positional arguments and you didn’t specify the args command variable, you might get an error like Error: unrecognized arguments: ..., as variable parsing is now based on argparse which doesn’t implicitly accept positional arguments. You can make your command backwards compatible by simply setting the args class variable. However, if you don’t have to keep compatibility with older Django versions, it’s better to implement the new add_arguments() method as described in Writing custom django-admin commands.

def add_arguments(self, parser):
    parser.add_argument('args', nargs='*')

添加上面的兼容性,破坏它是更新 django 的人的一个非常不明智的决定。