可以在 Django 之外使用 Django 数据库层吗?

我有一个很好的数据库,我已经在 Django 中创建,我想通过一些 Python 脚本 在外面接口,我的网站的东西。我很好奇是否可以在 Django 站点之外使用 Django 数据库 API,如果可以的话,有人知道如何做到这一点吗?谷歌在这方面还没有产生多少有用的结果。

29642 次浏览

You just need to configure the Django settings before you do any calls, including importing your models. Something like this:

from django.conf import settings
settings.configure(
DATABASE_ENGINE = 'postgresql_psycopg2',
DATABASE_NAME = 'db_name',
DATABASE_USER = 'db_user',
DATABASE_PASSWORD = 'db_pass',
DATABASE_HOST = 'localhost',
DATABASE_PORT = '5432',
TIME_ZONE = 'America/New_York',
)

Again, be sure to run that code before running, e.g.:

from your_app.models import *

Then just use the DB API as usual.

For using Django ORM from other applications you need:

1) export DJANGO_SETTINGS_MODULE=dproj.settings

2) Add your Django app folder to the path (you can do it in the code of your non-django-app):

sys.path = sys.path + ['/path/to/your/app/']

3) If using SQLite, use the full path to the db file in settings.py:

DATABASE_NAME = '/path/to/your/app/base.db'

Update setup_environ is to be removed in django 1.6

If you're able to import your settings.py file, then take a look at handy setup_environ command.

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


setup_environ(settings)


#here you can do everything you could in your project

A final option no-one's mentioned: a custom ./manage.py subcommand.

For django 1.5 on (multiple databases are supported) the DATABASE settings also changed. You need to adapt the previous answer to ...

settings.configure(
DATABASES = { 'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name',
'USER': 'db_usr',
'PASSWORD': 'db_pass',
'HOST': '',
'PORT': '',
}, },
TIME_ZONE = 'Europe/Luxembourg'
)

For django 1.7, I used the following to get up and running.

settings.py:

from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name',
'USER': 'usr',
'PASSWORD': 'secret',
'HOST': '127.0.0.1',
'PORT': '5432',
},
},
TIME_ZONE='America/Montreal',
)

In the file containing the startup routine

import os
import django


import v10consolidator.settings
from myapp.models import *


os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
"myapp.settings"
)
django.setup()
import os, sys


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))


from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


from app.models import MyModel

Based on the answer by Hai Hu, here is a working script, tested on Django 1.10 and 1.11. I first import Django's base apps because they are needed in many other apps.

import os
from django.conf import settings
from django.apps import apps


conf = {
'INSTALLED_APPS': [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sitemaps',
'django.contrib.sites',
'django.contrib.staticfiles',
'<your_app>',
],
'DATABASES': {
'default': {
'ENGINE': os.environ.get('DB_ENGINE'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
},
'TIME_ZONE': 'UTC'
}


settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)


<import your app models here>

Here is the code I use. Just replace your_project with your Django project name, yourApp with your Django app name, any_model with the model you want to use in models file and any_fild with the field you want to get from the database:

from django.conf import settings
import django


from your_project.settings import DATABASES, INSTALLED_APPS
settings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS)
django.setup()


from yourApp.models import *
print(any_model.objects.all()[0].any_fild)

I was looking for answers for django 3.0 and none of the above method exactly worked for me.

I read the official docs at https://docs.djangoproject.com/en/3.0/topics/settings/ and this scripts worked for me.

Project Structure

mysite
mysite
...
settings.py
db.sqlite3
db_tasks.py
manage.py
polls

db_tasks.py:

import os
import django


os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()


from polls.models import Question


print(Question.objects.all())
out: <QuerySet [<Question: WTU?]>

In Django >= V.3.2.3 Put the following before you model import

import os
import django


os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'mymodule.settings'
)
django.setup()
from app.models import MyModel

Then use your model as usual.

myitem = MyModel()
myitem.data = 'some data'
myitem.save()

Regards

for django 3+ :

#########################

directory and files structure:

--my_project

----my_project > settings.py

----myapps

##########################

import sys
sys.path.append("C:/Users/khder/Desktop/test/my_project") #append your main project directory path


import os
import django


#define your setting file as the following.
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'my_project.settings'
)
django.setup()


from my_app.models import MyModel
qs = MyModel.objects.all()
print(qs)

note: for path always use slash '/' not backslash '' even if you are using windows.

this is just example and change it based on your case/requirement.

i hope this helpful . done.