首先要編寫好自己的model
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=32,default='Title')
content = models.TextField(null=True)
然後
步驟:
命令行中進入 manage.py同級目錄
執行python manage.py makemigratetions app名(可選)
在執行python manage.py migrate
這樣就能通過model來自動映射生成數據庫,裏面的一個類就是一張數據表(ORM)
ORM
對象關係映射(Object Relation Mapping)
實現對象和數據庫的映射
隱藏數據訪問的細節,不需要編寫SQL語句
這樣就能在SQLite(數據庫)中插入數據了
在頁面呈現數據
後臺步驟
views.py中import models
article = models.Article.objects.get(pk=1) Article是自己設定的類 pk主鍵爲1 article是類中主鍵爲一的對象
render(request, htmlURL, { 'article' : article })通過渲染傳遞給前端
from django.shortcuts import render
from django.http import HttpResponse
from . import models
def index(request):
article = models.Article.objects.get(pk=1)
return render(request, 'blog/blog.html', {'article':article})
這樣在前端可以通過
{{ article.title }}
來獲取對象的title