昨天晚上凡伊,我們完成了一個(gè)簡單的實(shí)例來對(duì)數(shù)據(jù)庫表進(jìn)行操作赞枕。今天装哆,我們要熟悉更多的API,實(shí)現(xiàn)更復(fù)雜的功能承绸。這一步完成了,我們對(duì)小型數(shù)據(jù)的操作問題也就不大了挣轨。
現(xiàn)在军熏,我們還是參考django官方文檔,來進(jìn)行學(xué)習(xí)
1.構(gòu)造數(shù)據(jù)表
把以下內(nèi)容卷扮,拷貝到你的朋友charm中荡澎,然后執(zhí)行migrate命令
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self): # __unicode__ on Python 2
return self.name
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
def __str__(self): # __unicode__ on Python 2
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self): # __unicode__ on Python 2
return self.headline
2.創(chuàng)建對(duì)象
b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()
這樣,我們就把數(shù)據(jù)存進(jìn)去了
同一個(gè)對(duì)象晤锹,保存之后重新賦值摩幔,就會(huì)執(zhí)行修改操作
3.保存 ForeignKey 和 ManyToManyField 字段
現(xiàn)在,我們數(shù)據(jù)已經(jīng)保存了鞭铆,并已經(jīng)建立了關(guān)聯(lián)
在model中或衡,Entry關(guān)聯(lián)了外鍵Blog(ForeignKey)
所以在創(chuàng)建Entry的時(shí)候,要先獲取一個(gè)Blog對(duì)象车遂,給Entry賦值之后封断,才執(zhí)行保存數(shù)據(jù)庫的操作
entry = Entry(headline='test123', body_text='test123', pub_date=datetime.datetime.now(),
mod_date=datetime.datetime.now(), n_comments=123, n_pingbacks=456, rating=789)
cheese_blog = Blog.objects.get(name="Beatles Blog")
entry.blog = cheese_blog
entry.save()
現(xiàn)在處理ManyToManyField 的情況
存進(jìn)去了,還得能取出來:
data = entry.authors.iterator()
直接訪問屬性舶担,并把查詢集轉(zhuǎn)為可迭代
4.查詢對(duì)象
all_entries = Entry.objects.all()
5.按條件查詢
filter(**kwargs) 返回一個(gè)新的匹配查詢參數(shù)后的QuerySet
exclude(**kwargs) 返回一個(gè)新的不匹配查詢參數(shù)后的QuerySet
Entry.objects.filter(pub_date__year=2006)
q2 = q1.exclude(pub_date__gte=datetime.date.today())
6.鏈接查詢
Entry.objects.filter(headline__startswith='What')
.exclude(pub_date__gte=datetime.now())
.filter(pub_date__gte=datetime(2005, 1, 1))
7.延遲查詢
創(chuàng)建QuerySets不會(huì)觸及到數(shù)據(jù)庫操作坡疼,你可以多個(gè)過濾合并到一起,直到求值的時(shí)候django才會(huì)開始查詢
q = Entry.objects.filter(headline__startswith="What")
q = q.filter(pub_date__lte=datetime.now())
q = q.exclude(body_text__icontains="food")
8.檢索單個(gè)對(duì)象
one_entry = Entry.objects.get(pk=1)
9.限制查詢:分頁/排序查詢
Entry.objects.all()[:5]
Entry.objects.order_by('headline')[0:1].get()
10.字段查詢
Entry.objects.filter(pub_date__lte='2006-01-01')
轉(zhuǎn)換成SQL:
SELECT*FROMblog_entryWHEREpub_date <= '2006-01-01';
11.exact
Entry.objects.get(headline__exact="Man bites dog")
轉(zhuǎn)換成SQL:
SELECT ... WHERE headline = 'Man bites dog';
12.iexact——忽略大小寫
Blog.objects.get(name__iexact="beatles blog")
13.contains——包含查詢柄沮,區(qū)分大小寫
Entry.objects.get(headline__contains='Lennon')
轉(zhuǎn)換成SQL:
SELECT ... WHERE headline LIKE '%Lennon%';
icontains 不區(qū)分大小寫
startswith回梧,endswith废岂,istartswith祖搓,iendswith
前后模糊查詢
14.連接查詢
查詢blog__name匹配的,返回Entry
Entry.objects.filter(blog__name__exact='Beatles Blog')
查詢entry__headline匹配的湖苞,返回Blog
Blog.objects.filter(entry__headline__contains='Lennon')
如果跨越多層關(guān)系查詢拯欧,中間模型沒有值,django會(huì)作為空對(duì)待不會(huì)發(fā)生異常
Blog.objects.filter(entry__author__name='Lennon');
Blog.objects.filter(entry__author__name__isnull=True);
Blog.objects.filter(
entry__author__isnull=False,
entry__author__name__isnull=True);
15.F對(duì)象财骨,對(duì)字段進(jìn)行操作镐作。就像SQL中,A列+B列隆箩。F對(duì)象很少用
from django.db.models import F
Entry.objects.filter(n_pingbacks__lt=F('n_comments'))
列加減乘除都可以
Entry.objects.filter(n_pingbacks__lt=F('n_comments') * 2)
Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
Entry.objects.filter(author__name=F('blog__name'))
16.like語句轉(zhuǎn)義百分號(hào)
Entry.objects.filter(headline__contains='%')
轉(zhuǎn)義為:
SELECT ... WHERE headline LIKE '%\%%';
17.刪除
q = Entry.objects.filter(headline__startswith="What")
q.delete()
18.批量修改
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
一次性修改所有的Entry的blog屬性指向
b = Blog.objects.get(pk=1)
Entry.objects.all().update(blog=b)
update也可以使用F()
Entry.objects.update(headline=F('blog__name'))
19.One-to-many關(guān)系
e = Entry.objects.get(id=2)
print e.blog # Hits the database to retrieve the associated Blog
e = Entry.objects.select_related().get(id=2)
print e.blog # 不會(huì)在向數(shù)據(jù)庫取; 使用緩存中的值.
b = Blog.objects.get(id=1)
b.entry_set.all() # 返回所有blog的關(guān)聯(lián)對(duì)象.
# b.entry_set is a Manager that returns QuerySets.
b.entry_set.filter(headline__contains='Lennon')
b.entry_set.count()
b = Blog.objects.get(id=1)
b.entries.all() # 返回所有blog的關(guān)聯(lián)對(duì)象
# b.entries is a Manager that returns QuerySets.
b.entries.filter(headline__contains='Lennon')
b.entries.count()
add(obj1, obj2, ...) 把多個(gè)對(duì)象建立連接
create(**kwargs) 建立新對(duì)象
remove(obj1, obj2, ...) 移除多個(gè)關(guān)系對(duì)象
clear() 清理所有關(guān)系對(duì)象
20.Many-to-many關(guān)系
e = Entry.objects.get(id=3)
e.authors.all() # 返回Entry所有authors
e.authors.count()
e.authors.filter(name__contains='John')
a = Author.objects.get(id=5)
a.entry_set.all() # 返回Author所有entry
21.One-to-one關(guān)系
要在定義模型的時(shí)候設(shè)置
class EntryDetail(models.Model):
entry = models.OneToOneField(Entry)
details = models.TextField()
ed = EntryDetail.objects.get(id=2)
ed.entry # 返回 Entry 對(duì)象