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.
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.
Django doesn't have a separate package for it's ORM, but it's still possible to use it on its own.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With