自定义django-admin命令-方法未找到



运行django-admin命令时,找不到本地方法

update.py

class Command(NoArgsCommand):
    help = 'Help Test'
    def handle(self, **options):
        test1 = 'hello'
        doThis()
    def doThis():
        test2 = 'hello'

运行python3 manage.py update命令产生如下错误:

File "/opt/dir/app/management/commands/updatefm.py", line 25, in handle
        doThis()
    NameError: name 'doThis' is not defined

我在文档中找不到这样做的原因https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/#methods

关于Python如何处理类和对象,有两件事你没有注意到。

Command.handle正在调用来自同一类的方法doThis,因此您应该使用self:

def handle(self, **options):
    test1 = 'hello'
    self.doThis()

然后你应该更改doThis的签名,以便Python可以将其用作Command类的方法:

def doThis(self):
    test2 = 'hello'

最新更新