如何在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')

最佳答案

python manage.py loaddata */fixtures/*.json命令中的glob输入起作用,因为glob由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)

关于python - 带有文件名通配符的Django call_command(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56545965/

10-12 16:38