0

我在应用程序目录中编写了 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
4

2 回答 2

1

如果您计划多次运行此命令,我建议您创建一个自定义管理命令。它只需要少量样板代码和应用程​​序中的特殊目录。它将解决您的问题并帮助提高项目的长期可维护性。

https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

于 2013-06-26T02:53:17.017 回答
0

在编写独立的 Django 脚本时,您需要手动执行一些任务。

于 2013-06-26T02:19:07.503 回答