6

我想运行以下脚本来使用名称等预先填充我的模型......但我收到一个错误。脚本是

first_names = first_names.split('\n')
last_names = last_names.split('\n')
phones=[str(i) for i in range(2310000000,2310999999, 1563)]
emails = ['test%s@test.com' %i for i in range(0,144)]

import os
os.environ['DJANGO_SETTINGS_MODULE']='project.settings'

from customer.models import Customer
from django.contrib.auth.models import User

users = User.objects.all()

if __name__ == "__main__":
    for i in range(10):
        customer = Customer(first_name=choice(first_names), last_name=choice(last_names),
                        telephone=choice(phones),email=choice(emails), creator=choice(users))
        customer.save()

错误是

Traceback (most recent call last):
  File "populatedb.py", line 431, in <module>
    from customer.models import Customer
ImportError: No module named customer.models

dir_tree 是(如果我可以正确“绘制”它)

-project_dir
|
|--customer
|--|
   |--models.py(etc...)
|
|--project(the settings file is here)
|--
|--another_app
|--scripts (here is my python script)
4

3 回答 3

6

您可以将您的 sys 路径附加到您的脚本中,例如:

import sys
sys.path.append('/path/to/your/djangoproject/')

希望这可以帮助。

于 2013-11-26T15:05:36.627 回答
4

在设置为 os.environ var project_settings 之前添加这些行后,我的脚本工作了

script_path = os.path.dirname(__file__)
project_dir = os.path.abspath(os.path.join(script_path,'..','..','project_folder'))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE']='rhombus.settings'

谢谢你们!

于 2013-11-26T15:12:41.960 回答
4

您还可以创建自定义 django-admin 命令并使用以下命令执行它们 manage.pyhttps ://eli.thegreenplace.net/2014/02/15/programmatically-populating-a-django-database https://docs.djangoproject.com/en /2.1/howto/自定义管理命令/

于 2018-11-27T13:54:43.947 回答