我有一个简单的python文件,我最终想从chron运行。
看起来像这样:
from customers.models import Customer, NotificationLogEntry
def hello():
customers = Customer.objects.all()
for c in customers:
log_entry = NotificationLogEntry(
customer=c,
sent=True,
notification_type=0,
notification_media_type=0,
)
log_entry.save()
if __name__ == '__main__':
hello()
当我运行时:
python notifications.py
我收到导入错误:
Traceback (most recent call last):
File "notifications.py", line 1, in <module>
from customers.models import Customer, NotificationLogEntry
ImportError: No module named customers.models
这个模块存在,我在django app中没有任何问题地调用它。为什么我在应用程序之外收到此错误?
答案 0 :(得分:6)
您可以创建自定义命令
https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
或者,运行./manage.py shell
然后导入您的文件
或者,加载django设置
http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
答案 1 :(得分:3)
如果您正在执行cron作业,这是一个超级简单的选择:
cat run.py | ./manage.py shell
答案 2 :(得分:1)
您需要设置项目路径
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
# your imports, e.g. Django models
from customers.models import Customer, NotificationLogEntry