2017/1/15 1:02:05
Django學習筆記之數(shù)據模型
1 創(chuàng)建模型
首先我們在項目中創(chuàng)建一個數(shù)據模型:
from django.db import models
# Create your models here.
class SKBlog(models.Model):
title=models.CharField(max_length=100)
revisedTime=models.TextField()
content=models.TextField()
shortContent=models.TextField()
def __unicode__(self):
'''
輸出數(shù)據內容
:return:
'''
return '標題:'+self.title
創(chuàng)建的數(shù)據模型需要繼承models.Model
2 同步數(shù)據庫
在創(chuàng)建好了數(shù)據模型之后,我們需要進行同步數(shù)據庫操作:
注意:Django 1.7 及以上的版本需要用以下命令
python manage.py makemigrations
python manage.py migrate
在同步好數(shù)據庫中后我們就可以發(fā)現(xiàn)數(shù)據庫中多了SKBlog table了
3 使用數(shù)據模型
以數(shù)據模型保存數(shù)據:
⑴ 創(chuàng)建數(shù)據模型
SKBlog.objects.create(title=title,revisedTime=revisedTime,content=content,shortContent=shortContent)
或者
skBlog=SKBlog(title=title,revisedTime=revisedTime,content=content,shortContent=shortContent)
skBlog.save()
或者
skBlog=SKBlog()
skBlog.title=title
skBlog.revisedTime=revisedTime
skBlog.content=content
slBlog.shortContent=shortContent
skBlog.save()
或者
SKBlog.objeats.get_or_create(title=title,revisedTime=revisedTime,content=content,shortContent=shortContent)
這種方法是防止重復很好的方法,但是速度要相對慢些憎妙,返回一個元組季稳,第一個為SKBlog對象集灌,第二個為True或False, 新建時返回的是True, 已經存在時返回False.
⑵ 獲取數(shù)據模型
#獲取指定的一個
blog=SKBlog.objects.get(title='aaa')
#獲取所有
blogs=SKBlog.objects.all()
#切片操作,獲取前面十個
blogs=SKBlog.objects.all()[:10]