如何在call_command()
中使用文件名通配符?我正在尝试创建一个与python manage.py loaddata */fixtures/*.json
下面的代码抛出CommandError: No fixture named '*' found.
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Load all fixtures in app directories'
def handle(self, *args, **kwargs):
call_command('loaddata', '*/fixtures/*.json')
self.stdout.write('Fixtures loaded\n')
答案 0 :(得分:1)
python manage.py loaddata */fixtures/*.json
命令中的glob输入起作用是因为bash被bash扩展了;如果您尝试转义glob,例如python manage.py loaddata '*/fixtures/*.json'
,该命令应失败并显示相同的错误消息。
相反,扩展Python端的glob,例如:
import pathlib
class Command(BaseCommand):
help = 'Load all fixtures in app directories'
def handle(self, *args, **kwargs):
cmd_args = list(pathlib.Path().glob('*/fixtures/*.json'))
call_command('loaddata', *cmd_args)