讓Django支援多種資料庫

jieforest發表於2012-08-17
In a recent Django class one of my students posed the problem she was learning Django to tackle - she would be responsible for writing a web-based administrative interface to a database whose structure she wasn't allowed to modify. Can Django do that?

Absolutely - and Django even comes with a management command to bootstrap working with a legacy database. Let's create a brand new project, use a popular sample database as our target, and using Django's multi-db support to store Django's built-in model data in a separate database.

Installation and setup
For this project I'm using Django 1.3 since that's the version we targeted in the class. All code referenced in the tutorial will be checked into the github project and can be reviewed there. I'm using virtualenv and pip to manage installation of Django, my Python environment, and eventually my third party applications.

CODE:

$ mkdir dualdb-project
$ cd dualdb-project
$ mkvirtualenv django1.3
(django1.3)$ pip install django==1.3
...
Successfully installed django
Cleaning up...
(django1.3)$ django-admin.py startproject dualdb
(django1.3)$ ls dualdb
(django1.3)$ ls -l dualdb/
total 16
-rw-rw-r-- 1 simeon simeon    0 Aug  1 15:20 __init__.py
-rw-rw-r-- 1 simeon simeon  503 Aug  1 15:20 manage.py
-rw-rw-r-- 1 simeon simeon 5031 Aug  1 15:20 settings.py
-rw-rw-r-- 1 simeon simeon  565 Aug  1 15:20 urls.pyNow that I have a new Django project, I need a sample database to look at. The Chinook project provides a sample reference database in various database formats - think a new version of the old Northwind reference database. I downloaded the Sqlite version for our project from the Chinook project website and dropped it in my new dualdb folder. I'm also going to create a "chinook" app to work in.
  1. (django1.3)$ cd dualdb/
  2. (django1.3)$ chmod u+x manage.py 
  3. (django1.3)$ ./manage.py startapp chinook
  4. (django1.3)$ ls -l chinook
  5. total 12
  6. -rw-rw-r-- 1 simeon simeon   0 Aug  1 15:45 __init__.py
  7. -rw-rw-r-- 1 simeon simeon  57 Aug  1 15:45 models.py
  8. -rw-rw-r-- 1 simeon simeon 383 Aug  1 15:45 tests.py
  9. -rw-rw-r-- 1 simeon simeon  26 Aug  1 15:45 views.py

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-741253/,如需轉載,請註明出處,否則將追究法律責任。

相關文章