我正在尝试学习“如何在django中运行独立脚本”。 我使用的是python2.7和django == 1.4.3。 我创建了一个非常基本的脚本,我试图运行但面对 导入错误。我不想创建管理命令,因为这只是 临时的东西,我的重点是学习。
我的代码
import os
import sys
from cartridge.shop.models import HomepageUpselling
class HomepageUpsellingToBestsellers():
"""This class copy the HomepageUpselling data to BestSellers"""
def homepageuselling_to_bestsellers(self):
""" Data Copy """
hu_obj = HomepageUpselling.objects.all()
for hu_iterable in hu_obj:
bs_obj, created = \
BestSeller.objects.get_or_create(product=hu_iterable.product,
variation=hu_iterable.variation)
print "BestSeller data copying %s" % bs_obj.id
return
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.setttings")
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from django.core.management import execute_from_command_line
hu_to_bs_obj = HomepageUpsellingToBestsellers()
hu_to_bs_obj.homepageuselling_to_bestsellers()
print "Data Copied"
错误
ImportError: No module named cartridge.shop.models
答案 0 :(得分:1)
您正在使用Django 1.4所以这是编写环境的正确方法..
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
# you can import your model here and the locaion of function
from your_project_name.models import Location
# From here you can start your script..
答案 1 :(得分:1)
在我看来(特别是考虑到你的用例)这样做的最好方法是编写自己的管理命令。子类Basecommand
然后将其作为
python manage.py yourcommand arguments