DJangoメモ:はじめからの続きです。
モデルの作成と適用
以下のコマンドでアプリケーションを作成。プロジェクトは複数のアプリケーションから成る(たぶん)。
python manage.py startapp [polls]
[polls]( _init_.py models.py views.py が入ったディレクトリ)が作られるので、このmodels.pyを編集。
モデルの作成(models.py)
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
これらのクラスがモデルとなり、このモデルをもとにデータベーステーブルが構成される模様
ただ、この時点ではまだモデルを定義しているだけなので、今度は適用するためにsettings.pyを編集。
モデルの適用(settings.py)
# この部分を修正
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites', # ここと
'polls' # ここ。プロジェクトのルートディレクトリから辿っているらしい
)
ここでもう一度
python manage.py syncdb
を実行。すると以前作ったデータベースにテーブルが追加される。
データベースAPIの勉強
参考:http://www.djangoproject.jp/doc/ja/1.0/topics/db/queries.html#topics-db-queries