开发者

Can one use the Django database layer outside of Django?

I've got a nice database I've created in Django, and I'd like to interface with it through some python scripts outside of my website stuff. I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have an开发者_开发知识库y info on how it can be done? Google hasn't yielded many useful results for this.


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 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()


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


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?]>


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


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)


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'


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'
)


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜