Django Model都繼承自django.db.models.ModelModel當(dāng)中每一個(gè)屬性attribute都代表一個(gè)database fieldDjango Model API可以執(zhí)行數(shù)據(jù)庫的增刪改查, 而不需要寫一些數(shù)據(jù)庫的查詢語句Django項(xiàng)目建成后, 默認(rèn)設(shè)置了使用SQLite數(shù)據(jù)庫, 在my_blog/my_blog/setting.py中可以查看和修改數(shù)據(jù)庫設(shè)置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
還可以設(shè)置其他數(shù)據(jù)庫, 如MySQL, PostgreSQL, 現(xiàn)在為了簡單, 使用默認(rèn)數(shù)據(jù)庫設(shè)置
在my_blog/article/models.py下編寫如下程序:
from django.db import models
# Create your models here.
class Article(models.Model) :
title = models.CharField(max_length = 100) #博客題目
category = models.CharField(max_length = 50, blank = True) #博客標(biāo)簽
date_time = models.DateTimeField(auto_now_add = True) #博客日期
content = models.TextField(blank = True, null = True) #博客文章正文
def __unicode__(self) :
return self.title
class Meta: #按時(shí)間下降排序
ordering = ['-date_time']
其中__unicode__(self) 函數(shù)Article對(duì)象要怎么表示自己, 一般系統(tǒng)默認(rèn)使用`` 來表示對(duì)象, 通過這個(gè)函數(shù)可以告訴系統(tǒng)使用title字段來表示這個(gè)對(duì)象
CharField 用于存儲(chǔ)字符串, max_length設(shè)置最大長度TextField 用于存儲(chǔ)大量文本DateTimeField 用于存儲(chǔ)時(shí)間, auto_now_add設(shè)置True表示自動(dòng)設(shè)置對(duì)象增加時(shí)間 $ python manage.py migrate #命令行運(yùn)行該命令
因?yàn)槲覀円呀?jīng)執(zhí)行過該命令會(huì)出現(xiàn)如下提示
Operations to perform:
Apply all migrations: admin, contenttypes, sessions, auth
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
那么現(xiàn)在需要執(zhí)行下面的命令
$ python manage.py makemigrations
#得到如下提示
Migrations for 'article':
0001_initial.py:
- Create model Article
現(xiàn)在重新運(yùn)行以下命令
$ python manage.py migrate
#出現(xiàn)如下提示表示操作成功
Operations to perform:
Apply all migrations: auth, sessions, admin, article, contenttypes
Running migrations:
Applying article.0001_initial... OK
migrate命令按照app順序建立或者更新數(shù)據(jù)庫, 將
models.py與數(shù)據(jù)庫同步
現(xiàn)在我們進(jìn)入Django中的交互式shell來進(jìn)行數(shù)據(jù)庫的增刪改查等操作
$ python manage.py shell
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
這里進(jìn)入Django的shell和python內(nèi)置的shell是非常類似的
>>> from article.models import Article
>>> #create數(shù)據(jù)庫增加操作
>>> Article.objects.create(title = 'Hello World', category = 'Python', content = '我們來做一個(gè)簡單的數(shù)據(jù)庫增加操作')
>>> Article.objects.create(title = 'Django Blog學(xué)習(xí)', category = 'Python', content = 'Django簡單博客教程')
>>> #all和get的數(shù)據(jù)庫查看操作
>>> Article.objects.all() #查看全部對(duì)象, 返回一個(gè)列表, 無對(duì)象返回空list
[, ]
>>> Article.objects.get(id = 1) #返回符合條件的對(duì)象
>>> #update數(shù)據(jù)庫修改操作
>>> first = Article.objects.get(id = 1) #獲取id = 1的對(duì)象
>>> first.title
'Hello World'
>>> first.date_time
datetime.datetime(2014, 12, 26, 13, 56, 48, 727425, tzinfo=)
>>> first.content
'我們來做一個(gè)簡單的數(shù)據(jù)庫增加操作'
>>> first.category
'Python'
>>> first.content = 'Hello World, How are you'
>>> first.content #再次查看是否修改成功, 修改操作就是點(diǎn)語法
'Hello World, How are you'
>>> #delete數(shù)據(jù)庫刪除操作
>>> first.delete()
>>> Article.objects.all() #此時(shí)可以看到只有一個(gè)對(duì)象了, 另一個(gè)對(duì)象已經(jīng)被成功刪除
[]
Blog.objects.all() # 選擇全部對(duì)象
Blog.objects.filter(caption='blogname') # 使用 filter() 按博客題目過濾
Blog.objects.filter(caption='blogname', id="1") # 也可以多個(gè)條件
#上面是精確匹配 也可以包含性查詢
Blog.objects.filter(caption__contains='blogname')
Blog.objects.get(caption='blogname') # 獲取單個(gè)對(duì)象 如果查詢沒有返回結(jié)果也會(huì)拋出異常
#數(shù)據(jù)排序
Blog.objects.order_by("caption")
Blog.objects.order_by("-caption") # 倒序
#如果需要以多個(gè)字段為標(biāo)準(zhǔn)進(jìn)行排序(第二個(gè)字段會(huì)在第一個(gè)字段的值相同的情況下被使用到),使用多個(gè)參數(shù)就可以了
Blog.objects.order_by("caption", "id")
#連鎖查詢
Blog.objects.filter(caption__contains='blogname').order_by("-id")
#限制返回的數(shù)據(jù)
Blog.objects.filter(caption__contains='blogname')[0]
Blog.objects.filter(caption__contains='blogname')[0:3] # 可以進(jìn)行類似于列表的操作
當(dāng)然還有更多的API, 可以查看官方文檔