我在应用程序目录中编写了 python 文件,我想按名称从我的数据库中获取一个用户,然后在脚本中独立地做一些事情。
我尝试了以下方法:
from django.contrib.auth.models import User
user = User.objects.filter(username='xiaofei')
print user
但:
Traceback (most recent call last):
File "send_test.py", line 1, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 5, in <module>
from django.db import models
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 40, 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.
最终的解决方案:
import os, sys
sys.path.insert(0, os.path.join(os.path.abspath('..')))
import settings
from django.core.management import setup_environ
setup_environ(settings)
from django.contrib.auth.models import User
user = User.objects.filter(username='xiaofei')
print user