2009年2月5日木曜日

Django DBを使用するための設定

DBを使用するための設定

前回のプロジェクト名のフォルダmyprojectの中の
settings.py  ファイルを編集します。

1-1.MySQL を使用する場合

MySQLでDB test1 を作成しておきます。
そのDBにユーザ、パスワードを作成しておきます。
必要があれば、MySQL-python-1.2.2.win32-py2.5.exeをインストール

settings.py  ファイルを


DATABASE_ENGINE = 'mysql'      
DATABASE_NAME = 'test1'        
DATABASE_USER = 'test1'        
DATABASE_PASSWORD = 'passwd'    
DATABASE_HOST = 'localhost'    
DATABASE_PORT = '3306'         



INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'myproject.myapp',
)


1-2.SQLite3 を使用する場合

settings.py  ファイルを


DATABASE_ENGINE = 'sqlite3'    
DATABASE_NAME = 'test1.dat'     #DB file name
DATABASE_USER = ''            
DATABASE_PASSWORD = ''        
DATABASE_HOST = ''            
DATABASE_PORT = ''            



INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'myproject.myapp',
)

test1.datというDBファイルを作成する設定です。



1-3.PostgreSQL を使用する場合

PostgreSQLでDB test1 を作成しておきます。
そのDBにユーザ、パスワードを作成しておきます。

psycopg2-2.0.8.win32-py2.5-pg8.3.4-release.exe
をインストールしておきます。(バージョンは使用環境に合わせて)

settings.py  ファイルを


DATABASE_ENGINE = 'postgresql_psycopg2' 
DATABASE_NAME = 'test1'        
DATABASE_USER = 'test1'           
DATABASE_PASSWORD = 'passwd'         
DATABASE_HOST = 'localhost'          
DATABASE_PORT = '5432'            



INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'myproject.myapp',
)

あとそれぞれに、タイムゾーン、言語環境を設定
TIME_ZONE         = 'Japan/Tokyo' 
LANGUAGE_CODE     = 'ja-jp' 

各INSTALLED_APPSに
'myproject.myapp',とmodels.pyの位置を指定しておきます。

--------------

2.各テーブルの作成

プロジェクト名のフォルダの下のアプリケーション名のフォルダにある
models.pyを

from django.db import models

# Create your models here.

class Post(models.Model): #
    title = models.CharField(max_length=100)
    entry = models.CharField(max_length=400)
    updated_at = models.DateTimeField('date published')

と記載し

プロジェクト名のフォルダmyprojectで

myproject>manage.py syncdb

Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table myapp_post

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username: ユーザ名
E-mail address: メールアドレス
Password:パスワード
Password (again):パスワード
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Message model

でDBに各テーブルが作成されます。