天天看點

django 開發實戰--第四章建立部落格設計Model(即設計資料庫表)

1.設計Model(即設計資料庫表)

打開blog目錄下的models.py檔案,這是定義blog資料結構的地方。

django 開發實戰--第四章建立部落格設計Model(即設計資料庫表)
from django.db import models

# Create your models here.
class BlogsPost(models.Model):
    title = models.CharField(max_length = 150)  # 部落格标題
    body = models.TextField()                   # 部落格正文
    timestamp = models.DateTimeField()          # 建立時間
           

 2、再次執行資料庫同步

mysite> python manage.py makemigrations blog
Migrations for 'blog':
  blog\migrations\0001_initial.py
    - Create model BlogsPost

mysite> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying blog.0001_initial... OK
           

 這裡做一個小小的解釋:資料庫同步

python3 manage.py makemigrations chenshuai。報錯

django 開發實戰--第四章建立部落格設計Model(即設計資料庫表)

這裡應該同步的是INSTALLED_APPS 的APP。 一個項目下邊可以有多個APP

3、通過Admin 管理。

通過Admin背景來管理blog表資料。打開 admin.py 檔案。

from django.contrib import admin
from blog.models import BlogsPost


# Register your models here.
class BlogsPostAdmin(admin.ModelAdmin):
    list_display = ['title', 'body', 'timestamp']


admin.site.register(BlogsPost, BlogsPostAdmin)
           

4、登入Admin背景添加blog 

再次啟動項目,通路:http://127.0.0.0:8000/admin