Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django database layer outside of Django?

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

like image 397
gct Avatar asked Feb 01 '10 22:02

gct


People also ask

Can you use Django with an existing database?

In order to use an existing database in Django, you need to have a model for each table. Creating models for existing tables manually is just too much work. However, there's no need to do that, since Django has a builtin tool to solve this exact problem.

Can you use Django ORM standalone?

Django doesn't have a separate package for it's ORM, but it's still possible to use it on its own.

Can you use multiple databases within the same Django projects?

Django's admin doesn't have any explicit support for multiple databases. If you want to provide an admin interface for a model on a database other than that specified by your router chain, you'll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content.

Can you use Django without models?

Yes that is possible, but a lot of ways how Django can help with webdevelopment are based on its models. For example based on a model Django can make a ModelForm [Django-doc] to automate rendering HTML forms that map to the model, validating user input, and saving it to the database.


2 Answers

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.

like image 119
FogleBird Avatar answered Sep 21 '22 13:09

FogleBird


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() 
like image 35
Gab Avatar answered Sep 18 '22 13:09

Gab