2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DJangoメモ:はじめから(モデル設定編)

Last updated at Posted at 2013-12-09

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

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?