2010-02-06 64 views
3

你看看我的代碼之前,請參閱http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/爲什麼我的Django的代碼不能是「獨立的Django的腳本」

我想成爲一個獨立的Django的腳本

這是我的代碼:

from django.db import models 
from djangosphinx.models import SphinxSearch,SphinxQuerySet 


import os 
os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings" 

from django.core.management import setup_environ 
from sphinx_test import settings 

setup_environ(settings) 

DJANGO_SETTINGS_MODULE=sphinx_test.settings 

class File(models.Model): 
    name = models.CharField(max_length=200) 
    tags = models.CharField(max_length=200) 

    objects = models.Manager() 
    search = SphinxQuerySet(index="test1") 


import datetime 


class Group(models.Model): 
    name = models.CharField(max_length=32) 

class Document(models.Model): 
    group  = models.ForeignKey(Group) 
    date_added = models.DateTimeField(default=datetime.datetime.now) 
    title  = models.CharField(max_length=32) 
    content  = models.TextField() 

    search  = SphinxQuerySet(File,index="test1") 

    class Meta: 
     db_table = 'documents' 

,這是回溯:

Traceback (most recent call last): 
    File "D:\zjm_code\sphinx_test\models.py", line 1, in <module> 
    from django.db import models 
    File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module> 
    if not settings.DATABASE_ENGINE: 
    File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__ 
    self._setup() 
    File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup 
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) 
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. 

回答

3

您用來設置Django的代碼設置模塊必須在任何與django相關的代碼之前出現,包括腳本頂部的django db導入。

相關問題