目錄
#博客 class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __unicode__(self): return self.name #作者 class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __unicode__(self): return self.name #目錄 class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateTimeField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __unicode__(self): return self.headline
1.1.2 創(chuàng)建對象 用python對象描述數(shù)據(jù)庫表的數(shù)據(jù),django使用一個直觀的系統(tǒng),一個模型類描述一個數(shù)據(jù)表,一個類的實例描述表的一條詳細記錄。使用模型的save()方法將對象創(chuàng)建到數(shù)據(jù)庫。 from mysite.blog.models import Blog b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') b.save() 只有執(zhí)行save方法時,django才會執(zhí)行sql把對象寫入數(shù)據(jù)庫。
保存修改仍然使用save()方法 b5.name = 'New name' b5.save()
cheese_blog = Blog.objects.get(name="Cheddar Talk") entry.blog = cheese_blog #為 ManyToManyField 增加記錄 entry.save()
檢索表中所有數(shù)據(jù),最簡單的方式是用all(). all_entries = Entry.objects.all()
檢索過濾特定查詢結(jié)果,有兩個方法。 Entry.objects.filter(pub_date__year=2006)
Entry.objects.filter(headline__startswith='What') .exclude(pub_date__gte=datetime.now()) .filter(pub_date__gte=datetime(2005, 1, 1))
每次你完成一個QuerySet,你獲得一個全新的結(jié)果集,不包括前面的。每次完成的結(jié)果集是可以貯存,使用或復用 q1 = Entry.objects.filter(headline__startswith="What") q2 = q1.exclude(pub_date__gte=datetime.now()) q3 = q1.filter(pub_date__gte=datetime.now()) 三個QuerySets是分開的,第一個是headline以"What"單詞開頭的結(jié)果集,第二個是第一個的子集,即pub_date不大于現(xiàn)在的,第三個是第一個的子集 ,pub_date大于現(xiàn)在的
QuerySets是延遲的,創(chuàng)建QuerySets不會觸及到數(shù)據(jù)庫操作,你可以多個過濾合并到一起,直到求值的時候django才會開始查詢。如: q = Entry.objects.filter(headline__startswith="What") q = q.filter(pub_date__lte=datetime.now()) q = q.exclude(body_text__icontains="food") print q 雖然看起來執(zhí)行了三個過濾條件,實際上最后執(zhí)行print q的時候,django才開始查詢執(zhí)行SQL到數(shù)據(jù)庫。
使用python的數(shù)組限制語法限定QuerySet,如: Entry.objects.all()[:5]
取第五個到第十個 Entry.objects.all()[5:10]
一般的,限制QuerySet返回新的QuerySet,不會立即求值查詢,除非你使用了"step"參數(shù) Entry.objects.all()[:10:2] Entry.objects.order_by('headline')[0] Entry.objects.order_by('headline')[0:1].get()
字段查找是指定SQL語句的WHERE條件從句,通過QuerySet的方法filter(), exclude()和get()指定查詢關(guān)鍵字。 Entry.objects.filter(pub_date__lte='2006-01-01') 轉(zhuǎn)換為SQL: SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01'; 如果你傳了無效的參數(shù)會拋異常
數(shù)據(jù)庫API 支持一些查詢類型,下面體驗一下: Entry.objects.get(headline__exact="Man bites dog") 等價于 SELECT ... WHERE headline = 'Man bites dog'; 如果查詢沒有提供雙下劃線,那么會默認 __exact= Blog.objects.get(id__exact=14) # Explicit form Blog.objects.get(id=14) # __exact is implied b、iexact——忽略大小寫 Blog.objects.get(name__iexact="beatles blog") blog title會匹配 "Beatles Blog", "beatles blog", 甚至 "BeAtlES blOG". c、contains——包含查詢,區(qū)分大小寫 Entry.objects.get(headline__contains='Lennon') 轉(zhuǎn)化為SQL SELECT ... WHERE headline LIKE '%Lennon%'; icontains 不區(qū)分大小寫 startswith,endswith,istartswith,iendswith
Entry.objects.filter(blog__name__exact='Beatles Blog') 這個可以跨越你想要的深度。 反向跨關(guān)系查詢 Blog.objects.filter(entry__headline__contains='Lennon')
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);
目前給的例子里,我們建立了過濾,比照模型字段值和一個固定的值,但是如果我們想比較同一個模型里的一個指端和另一個字段的值,django提供F()——專門取對象中某列值的操作 from django.db.models import F Entry.objects.filter(n_pingbacks__lt=F('n_comments')) 注:n_pingbacks、n_comments為模型Entry屬性 django支持加減乘除和模計算 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'))
主鍵查詢捷徑 Blog.objects.get(id__exact=14) # Explicit form Blog.objects.get(id=14) # __exact is implied Blog.objects.get(pk=14) # pk implies id__exact
不僅限于__exact 查詢 # Get blogs entries with id 1, 4 and 7 Blog.objects.filter(pk__in=[1,4,7]) # Get all blog entries with id > 14 Blog.objects.filter(pk__gt=14)
跨越查詢 Entry.objects.filter(blog__id__exact=3) # Explicit form Entry.objects.filter(blog__id=3) # __exact is implied Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
like語句轉(zhuǎn)義百分號 Entry.objects.filter(headline__contains='%') 轉(zhuǎn)義為 SELECT ... WHERE headline LIKE '%\%%';
每個QuerySet都包含一個緩存,以盡量減少對數(shù)據(jù)庫的訪問。理解他的工作原理很重要,可以寫出最高效的代碼。 print [e.headline for e in Entry.objects.all()] print [e.pub_date for e in Entry.objects.all()] 這樣意味著數(shù)據(jù)庫查詢會執(zhí)行兩次,實際兩次數(shù)據(jù)庫加載 為了避免這個問題,簡單保存QuerySet復用 queryset = Poll.objects.all() print [p.headline for p in queryset] # Evaluate the query set. print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.
比較兩個模型實例,使用python標準的運算符,兩個等號== some_entry == other_entry some_entry.id == other_entry.id some_obj == other_obj some_obj.name == other_obj.name
刪除方法是很方便的,方法名為delete(),這個方法直接刪除對象沒有返回值 e.delete() 你也可以批量刪除對象,每個QuerySet有一個delete()方法,能刪除 QuerySet里所有對象
有時候你想給QuerySet里所有對象的一個字段賦予特定值,你可以使用 update()方法 # Update all the headlines with pub_date in 2007. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
這個方法只能用于無關(guān)聯(lián)字段和外鍵 b = Blog.objects.get(pk=1) # Change every Entry so that it belongs to this Blog. Entry.objects.all().update(blog=b)
update()方法不返回任何值,QuerySet不支持save方法,如果要執(zhí)行save,可以如下: for item in my_queryset: item.save()
update也可以使用F() # THIS WILL RAISE A FieldError Entry.objects.update(headline=F('blog__name'))
1.3.2 關(guān)系對象 當你在model里定義一個關(guān)系時,模型實例會有一個方便的API來訪問關(guān)系對象。用本頁上面的模型舉個例子,一個Entry
如果一個對象有ForeignKey,這個模型實例訪問關(guān)系對象通過簡單的屬性 e = Entry.objects.get(id=2) e.blog # Returns the related Blog object. 你可以憑借外鍵屬性獲取和賦值,修改外鍵值知道執(zhí)行save()方法才會保存到數(shù)據(jù)庫 e = Entry.objects.get(id=2) e.blog = some_blog e.save() 如果ForeignKey 設(shè)置了null=True 你可以賦值為None e = Entry.objects.get(id=2) print e.blog # Hits the database to retrieve the associated Blog. print e.blog # 不會在向數(shù)據(jù)庫取; 使用緩存中的值. e = Entry.objects.select_related().get(id=2) print e.blog # 不會在向數(shù)據(jù)庫取; 使用緩存中的值. print e.blog # 不會在向數(shù)據(jù)庫取; 使用緩存中的值. b = Blog.objects.get(id=1) b.entry_set.all() # 返回所有blog的關(guān)聯(lián)對象. # 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)對象 # b.entries is a Manager that returns QuerySets. b.entries.filter(headline__contains='Lennon') b.entries.count()
add(obj1, obj2, ...) 增加多個關(guān)系對象 b = Blog.objects.get(id=1) b.entry_set = [e1, e2]
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 .
class EntryDetail(models.Model): entry = models.OneToOneField(Entry) details = models.TextField() ed = EntryDetail.objects.get(id=2) ed.entry # 返回 Entry 對象.
|
|