django中的models
- 一個model對應數(shù)據(jù)庫中的一張表
- model以類的形式表現(xiàn)出來 包含了基本字段和數(shù)據(jù)行為
- 以創(chuàng)建類的形式來操作數(shù)據(jù)庫
- ORM 對象關心映射 隱藏細節(jié)不需要關心sql
步驟
- 創(chuàng)建類 繼承models.Model 該類即為一張數(shù)據(jù)表
- 在類中創(chuàng)建字段
- 生成數(shù)據(jù)表 進入命令行 輸入 python manage.py maekmigrations blog 在執(zhí)行 python manage.py migrate
class Article(models.Model):
title = models.CharField(max_length=32,default='Title')
content = models.CharField(null=True)
#views.py
from django.shortcuts import render
from django.http import HttpResponse
from . import models
def index(request):
artilvr = models.Article.objects.get(pk=1)
return render(request,'blog/index.html',{'artivlr':artilvr})
#index.html
<body>
<h1>
{{ artivlr.title }}
</h1>
<h3>
{{ artivlr.content }}
</h3>
</body>