Wednesday, June 6, 2012

Django -- create a new app - part1

為了方便管理全部的apps
所以先在外層的mutarock資料夾開一個apps的app
將來這個project裡面全部的app都放進去這裡
cd //var/www/mutarock
python manage.py startapp apps
以後的app都把它放在這麼資料夾下面
下面用tutorial的範例,簡單的投票系統做例子
cd /apps
python ./manage.py startapp polls
目前整個project的資料夾應該像下面這樣
mutarock/
    manage.py
    mutarock/
    apps/    
        polls/
polls則是長這個樣子
polls/
    __init__.py
    models.py
    tests.py
    views.py
models.py主要是這個app的資料型態,例如這個例子裡面有Poll和Choice
Poll 是只個別的投票
Choice 是各個選項
views.py則是一些動作,例如針對request做運算,或是回傳一些資料資料給使用者

實際開始編輯models.py
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
其他細節就不多說了,可以去看教學
只記錄下幾個關鍵
建立完新的app之後要記得去啟動他
到專案的資料夾下面

cd //var/www/mutarock/mutarock
vim settings.py
其中一個欄位是INSTALLED_APPS,在這邊把自己的app加進去
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'apps.polls', #這個範例的app
)
OK之後可以利用強大的managa.py去顯示這個app會建立的哪些table有哪些欄位(based on your model)
python manage.py sql polls
確定應該沒有問題之後就輸入
python manage.py syncdb
系統就會實際把table建好


============================================================
PS 建立完之後可以利用
python manage.py shell
這個語法去實際和系統互動 以下是教學提供的幾個例子,我就貼過來自己看
>>> from polls.models import Poll, Choice   # Import the model classes we just wrote.

# No polls are in the system yet.
>>> Poll.objects.all()
[]

# Create a new Poll.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> p.save()

# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1

# Access database columns via Python attributes.
>>> p.question
"What's new?"
>>> p.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<utc>)

# Change values by changing the attributes, then calling save().
>>> p.question = "What's up?"
>>> p.save()

# objects.all() displays all the polls in the database.
>>> Poll.objects.all()
[<Poll: Poll object>]
可以看到最後一個例子回傳的東西相當不人性化
看不出來是什麼鬼
所以可以在原來的models.py裡面加一些東西,讓資料顯示更明顯
class Poll(models.Model):
    # ...
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __unicode__(self):
        return self.choice
教學上面提到,熟悉python的人一般會使用 __str__ 而不是 __unicode__
這邊會建議使用 __unicode__ 是因為django預設是用unicode

No comments: