如何使用manage.py在同一目录中运行另一个python文件

时间:2019-07-12 14:20:27

标签: django django-rest-framework django-manage.py

我克隆了一个GitHub存储库。一切正常。但是我需要填充所有端点的样本数据。大约有20个文件,每个端点都有示例数据。然后在根文件夹中有一个文件(dataload.py),该文件应调用所有这20个文件并填充数据库。

我运行python dataload.py,但出现错误

File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

Dataload image

这是dataload.py的内容

from subprocess import call

print ('**** starting ***')

SETTINGS_FILE= 'promedic.settings_prod'
# SETTINGS_FILE= 'promedic.settings'

call(['python', 'manage.py', 'makemigrations', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'migrate', '--settings=%s'% SETTINGS_FILE])


call(['python', 'manage.py', 'loaddata', 'core/fixtures/allergies.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/blood_group.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/disabilities.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/drug-forms.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/drug-brands.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/dispense-types.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/genotypes.json', '--settings=%s'% SETTINGS_FILE])
call(['python', 'manage.py', 'loaddata', 'core/fixtures/states.json', '--settings=%s'% SETTINGS_FILE])

我将dataload.py更改为

from django.core.management import call_command
#from subprocess import call

print ('**** starting ***')

SETTINGS_FILE= 'promedic.settings_prod'
# SETTINGS_FILE= 'promedic.settings'
'''
call_command('makemigrations', )
call_command('migrate')
'''
call_command('loaddata', 'core/fixtures/allergies.json', settings='SETTINGS_FILE')
call_command('loaddata', 'core/fixtures/blood_group.json', settings='SETTINGS_FILE')

现在出现此错误

in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

1 个答案:

答案 0 :(得分:0)

有一个第三方库django-extensions link可以为您完成这项工作。在您的一个应用中创建一个scripts文件夹,然后从中运行所需的python脚本,或者看起来像是对夹具数据进行加载,您可以从脚本中加载这些夹具。

说的应用程序结构就是这样

|-main_app
      | - models.py ... ( etc )
      | - fixture_folder
           |-fixtures
      | - scripts_folder
           | - __init__.py
           | load_data.py
| - manage.py

您的load_data.py可能会这样

from django.core.management import call_command


def run():
    call_command('loaddata', 'fixture_file.json')

call_command实际上可以做很多事情link