第 8 章    資料模型

▸ 建立 Article, Comment model

article/models.py
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=128, unique=True)
    content = models.TextField()

    def __str__(self):
        return self.title


class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    content = models.CharField(max_length=128)

    def __str__(self):
        return self.article.title + '-' + str(self.id)

▸ 在管理者頁面檢視資料

article/admin.py
from django.contrib import admin
from article.models import Article, Comment


admin.site.register(Article)
admin.site.register(Comment)

▸ 設定 Django 環境

populate/base.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.settings')
import django
django.setup()

▸ 文章與留言填充程式

populate/article.py
from populate import base
from article.models import Article, Comment


titles = ['如何像電腦科學家一樣思考', '10分鐘內學好Python', '簡單學習Django']
comments = ['文章真棒', '並不認同您的觀點', '借分享', '學好一個程式語言或框架並不容易']


def populate():
    print('Populating articles and comments ... ', end='')
    Article.objects.all().delete()
    Comment.objects.all().delete()

    for title in titles:
        article = Article()
        article.title = title
        for j in range(20):
            article.content += title + '\n'
        article.save()
        for comment in comments:
            Comment.objects.create(article=article, content=comment)
    print('done')


if __name__ == '__main__':
    populate()

▸ 建立管理者帳號之填充程式

populate/admin.py
from populate import base
from django.contrib.auth.models import User


def populate(): 
    print('Creating admin account ... ', end='')
    User.objects.all().delete()
    User.objects.create_superuser(username='admin', password='admin', email=None)
    print('done')


if __name__ == '__main__':
    populate()

▸ 建立其他使用者帳號之填充程式

populate/users.py
from populate import base
from django.contrib.auth.models import User


def populate(): 
    print('Creating user accounts ... ', end='')
    User.objects.exclude(is_superuser=True).delete()
    for i in range(5):
        username = 'user' + str(i)
        User.objects.create_user(username=username, password=username, email=None)
    print('done')


if __name__ == '__main__':
    populate()

▸ 整合所有填充程式

populate/local.py
from populate import admin, users, article


admin.populate()
users.populate()
article.populate()

▸ 客製化管理者頁面

article/admin.py
from django.contrib import admin
from article.models import Article, Comment


class CommentAdmin(admin.ModelAdmin):
    list_display = ['article', 'content']
    list_display_links = ['article']
    list_filter = ['article', 'content']
    search_fields = ['content']
    list_editable = ['content']
 
    class Meta:
        model = Comment


admin.site.register(Article)
admin.site.register(Comment, CommentAdmin)

▸ 增加 Model 欄位

article/models.py
class Article(models.Model):
    title = models.CharField(max_length=128, unique=True)
    content = models.TextField()
    pubDateTime = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-pubDateTime']


class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    content = models.CharField(max_length=128)
    pubDateTime = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.article.title + '-' + str(self.id)

    class Meta:
        ordering = ['pubDateTime']

▸ 在管理者頁面顯示日期時間欄位

article/admin.py
...

class CommentAdmin(admin.ModelAdmin):
    list_display = ['article', 'content', 'pubDateTime']
    ...
Ubuntu

▸ 刪除再重建資料庫

$ sudo -i -u postgres
[sudo] password for <username>:
postgres@<username>:~$ dropdb blogdb
postgres@<username>:~$ createdb blogdb
postgres@<username>:~$ psql
postgres=# grant all privileges on database blogdb to dbuser;
GRANT
postgres=# \q
postgres@:~$ exit

Windows

▸ 刪除再重建資料庫

> cd C:\Program Files\PostgreSQL\11\bin
> set PGUSER=postgres
> set PGPASSWORD=postgres
> dropdb blogdb
> createdb blogdb
> psql
postgres=# grant all privileges on database blogdb to dbuser;
GRANT
postgres=# \q
Mac

▸ 刪除再重建資料庫

$ dropdb blogdb
$ createdb blogdb
$ psql postgres
<username>=# grant all privileges on database blogdb to dbuser;
GRANT
<username>=# \q

▸ 在 Git 忽略檔裡排除遷移檔

.gitignore
*~
__pycache__
*.pyc
00*.py

▸ 本章完成專案:blog8.zip