はじめての Django アプリ作成、その 1

最近Djangoチュートリアルをやっている。このエントリーではチュートリアルで書かれていない事について、補足する意味で備忘録をまとめる。

Djangoチュートリアル
http://djangoproject.jp/doc/ja/1.0/index.html


はじめての Django アプリ作成、その 1
http://djangoproject.jp/doc/ja/1.0/intro/tutorial01.html#intro-tutorial01



DjangoMySQLがインストールされている状態からスタート


MySQLの起動

意外と忘れている事だが、MySQLを起動しておく。

[daq@localhost ~]$ su
パスワード:
[root@localhost daq]# /etc/init.d/mysqld start
MySQL を起動中: [ OK ]
[root@localhost daq]# exit
exit


settings.pyの設定

シェルに対してdjango-admin.py startproject mysiteを叩くと、mysiteディレクトリが作成され、中に必要なファイルが自動生成される。Djangoのプロジェクト設定ファイルであるsettings.pyの設定を進めていく。チュートリアルでは、一般的に使われているデータベース全般について書かれている。特にSQliteの場合は、複数の設定項目をスキップできるので簡単に見える。

私はMySQLを使いたいので、MySQL向けのsettings.pyの記述についてまとめる。


DATABASES = {
'default': {
'ENGINE': 'mysql',          # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'django', # Or path to database file if using sqlite3.
'USER': '****', # Not used with sqlite3.
'PASSWORD': '********', # Not used with sqlite3.
'HOST': '/var/lib/mysql/mysql.sock',# Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
実際の設定は上のようになる、****の部分はMySQLのユーザーネームとパスワードを設定して欲しい。
またHOSTは、通常データベースの接続先のホストを指定するので、データベースとDjangoが同じホスト内にいればlocalhostと設定する。ただし、MySQLの場合Unixソケットを介して接続するのでパスを指定する必要がある。Unixソケットの確認方法は、MySQLインタープリターに対してstatusコマンドを叩くと確認できる。
[daq@localhost ~]$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql> status

                          • -

mysql Ver 14.12 Distrib 5.0.77, for redhat-linux-gnu (i686) using readline 5.1

Connection id: 2
Current database:
Current user: ****@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.0.77 Source distribution
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/lib/mysql/mysql.sock
Uptime: 16 hours 58 min 55 sec

下の方にあるUNIX socket:/var/lib/mysql/mysql.sockをsettingus.pyのHOSTに設定する。


DjangoMySQLの接続

シェルに向かってpython manage.py syncdbコマンドを叩くと、DjangoMySQLにアクセスして、データベースに必要なテーブルを作成する。

[daq@localhost toy]$ python manage.py syncdb
/usr/lib/python2.4/site-packages/django/db/__init__.py:60: DeprecationWarning: Short names for ENGINE in database configurations are deprecated. Prepend default.ENGINE with 'django.db.backends.'
DeprecationWarning
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site


ちなみにDjangoがMySQLに作成したテーブルは以下の通り


mysql> use django
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;

                                                          • +
Tables_in_django
                                                          • +
auth_group
auth_group_permissions
auth_message
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_content_type
django_session
django_site
                                                          • +

10 rows in set (0.00 sec)

mysql>



APIで遊んでみる


>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[]
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
>>> p.save()
>>> p.id
1
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 7, 15, 12, 00, 53)
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()
>>> Poll.objects.all()
[]

といった具合に、Django越しにMySQLをいじれた。