Django學(xué)習(xí)筆記之?dāng)?shù)據(jù)模型

2017/1/15 1:02:05


Django學(xué)習(xí)筆記之?dāng)?shù)據(jù)模型

1 創(chuàng)建模型

首先我們在項(xiàng)目中創(chuàng)建一個(gè)數(shù)據(jù)模型:

    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ù)據(jù)內(nèi)容
            :return:
            '''
        return '標(biāo)題:'+self.title

創(chuàng)建的數(shù)據(jù)模型需要繼承models.Model

2 同步數(shù)據(jù)庫

在創(chuàng)建好了數(shù)據(jù)模型之后,我們需要進(jìn)行同步數(shù)據(jù)庫操作:

    注意:Django 1.7 及以上的版本需要用以下命令
    python manage.py makemigrations
    python manage.py migrate

在同步好數(shù)據(jù)庫中后我們就可以發(fā)現(xiàn)數(shù)據(jù)庫中多了SKBlog table了

3 使用數(shù)據(jù)模型

以數(shù)據(jù)模型保存數(shù)據(jù)

⑴ 創(chuàng)建數(shù)據(jù)模型

    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)

這種方法是防止重復(fù)很好的方法,但是速度要相對慢些,返回一個(gè)元組,第一個(gè)為SKBlog對象,第二個(gè)為True或False, 新建時(shí)返回的是True, 已經(jīng)存在時(shí)返回False.

⑵ 獲取數(shù)據(jù)模型

    #獲取指定的一個(gè)
    blog=SKBlog.objects.get(title='aaa')
    #獲取所有
    blogs=SKBlog.objects.all()
    #切片操作,獲取前面十個(gè)
    blogs=SKBlog.objects.all()[:10]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容