《Django By Example》讀書筆記 02

項目(Projects)和應用(applications)的區別
在Django中,項目是一個大的集合,應用是項目的一個模塊,例如模板,視圖,URL等和framework交互,提供某種特定功能,可複用。

創建一個應用

python manage.py startapp blog

在同級目錄會看到blog文件夾,
這裏寫圖片描述

admin.py: 將blog註冊到Django administration site。
migrations: 放置應用的數據庫,允許Django追蹤模型變化,同步數據庫。
models.py: 應用數據模型,Django應用都要有這個文件,文件內容可以爲空。
tests.py: 在此添加應用測試。
views.py: 接收處理http請求,返回相應。

設計blog的數據結構
在models.py添加以下代碼

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
    STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
    unique_for_date='publish')
    author = models.ForeignKey(User,
    related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
    choices=STATUS_CHOICES,
    default='draft')
    class Meta:
    ordering = ('-publish',)
    def __str__(self):
    return self.title

這裏是blog的post基礎模型

  1. title:post的title,CharField類型,會轉成SQL數據庫的VARCHAR column
  2. SlugField只能包含字母,數字,下劃線和連字符的字符串,通常被用於URLs表示。
  3. author: This field is ForeignKey. This field defines a many-to-one relationship. We are telling Django that each post is written by a user and a user can write several posts. For this field, Django will create a foreign key in the database using the primary key of the related model. In this case, we are relying on the User model of the Django authentication system. We specify the name of the reverse relationship, from User to Post, with the related_name attribute. We are going to learn more about this later.
  4. body: This is the body of the post. This field is TextField, which translates into a TEXT column in the SQL database.
  5. publish: This datetime indicates when the post was published. We use Django’s timezone now method as default value. This is just a timezone-aware datetime.now.
  6. created: This datetime indicates when the post was created. Since we
    are using auto_now_add here, the date will be saved automatically when
    creating an object.
    updated: This datetime indicates the last time the post has been updated.
    Since we are using auto_now here, the date will be updated automatically
    when saving an object.
    status: This is a field to show the status of a post. We use a choices
    以上內容懶得翻譯了,自己看吧
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章