我有Django模型的夹具JSON文件,我想通过python脚本更新数据。我不想在终端python manage.py loaddata fixture.json
上运行命令。我想通过python脚本来做。
我为Django创建了虚拟环境。我还想通过脚本启动虚拟环境。我写了一个小脚本,但它没有用。
from subprocess import call
from os import chdir, getcwd
original_directory = getcwd()
chdir('/home/naresh/test_django')
call('source bin/activate', shell = True)
chdir('graphossss/')
call('python manage.py loaddata background/fixtures.json', shell= True)
chdir(original_directory)
收到错误:
“文件”manage.py“,第8行,
来自django.core.management import execute_from_command_line
ImportError:没有名为django.core.management的模块“
这意味着虚拟环境未激活...
答案 0 :(得分:2)
我通过调用call_command方法
解决了这个问题from django.core.management import call_command
call_command('loaddata', 'data.json', stdout=out, verbosity=0)
答案 1 :(得分:0)
Subprocess.call
将命令行的每个选项用作单独的参数。
例如:
from subprocess import call
from os import chdir, getcwd
original_directory = getcwd()
chdir('/home/naresh/test_django')
call('source', 'bin/activate')
call('python', 'manage.py', 'loaddata', 'fixtures.json')
chdir(original_directory)