如何从命令行运行django python文件

问题描述:

我有一个简单的python文件,我最终希望从chron运行。如何从命令行运行django python文件

它看起来像这样:

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应用程序中的任何问题。为什么我在我的应用程序之外获得这个错误?

您可以创建自定义命令

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/

需要设置up项目路径

import os 

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings") 

# your imports, e.g. Django models 
from customers.models import Customer, NotificationLogEntry