真想抽死自己。
python manage.py shell
這句話,決定可以將環境變量,也就是sys.path的環境變量值給你。而不是python的編譯環境
/////////////////////////////////////////////下面弄了點翻譯/////////////////////////////////////////
?
生成查詢
?
你創建完數據模型,django會自動提供給你數據庫抽象的API,可以創建,獲取,修改,刪除對象.本篇文檔講解如何使用API。
?
我們參考下面模型,一個weblog:
- 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??
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
?
創建對象
?
用python對象描述數據庫表的數據,django使用一個直觀的系統,一個模型類描述一個數據表,一個類的實例描述表的一條詳細記錄。使用模型的save()方法將對象創建到數據庫。
- >>>? from ?mysite.blog.models? import ?Blog ??
- >>>?b?=?Blog(name= 'Beatles?Blog' ,?tagline= 'All?the?latest?Beatles?news.' ) ??
- >>>?b.save()??
>>> from mysite.blog.models import Blog >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') >>> b.save()
?只有執行save方法時,django才會執行sql把對象寫入數據庫。
?
保存修改的對象
?
保存修改仍然使用save()方法
- >>?b5.name?=? 'New?name' ??
- >>?b5.save()??
>> b5.name = 'New name' >> b5.save()
?
保存 ForeignKey 和 ManyToManyField 字段
?
- >>>?cheese_blog?=?Blog.objects.get(name= "Cheddar?Talk" ) ??
- >>>?entry.blog?=?cheese_blog ??
- >>>?entry.save()??
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk") >>> entry.blog = cheese_blog >>> entry.save()
為 ManyToManyField 增加記錄
?
- >>?joe?=?Author.objects.create(name= "Joe" ) ??
- >>?entry.authors.add(joe)??
>> joe = Author.objects.create(name="Joe") >> entry.authors.add(joe)
?
檢索對象
?
從數據庫里檢索對象?,可以通過模型的Manage來建立QuerySet,一個queryset表現為一個數據庫中對象的結合,他可以有0個一個或多個過濾條件,在SQL里QUERYSET相當于SELECT 語句用 WHERE ?或 LIMIT過濾。
你通過模型的manager來獲取QUERYSET,每個模型至少有一個manager
- <TT? class = "docutils?literal" >>>>?Blog.objects ??
- <django.db.models.manager.Manager?object?at?...> ??
- >>>?b?=?Blog(name= 'Foo' ,?tagline= 'Bar' ) ??
- >>>?b.objects ??
- Traceback: ??
- ????... ??
- AttributeError:? "Manager?isn't?accessible?via?Blog?instances." ??
- </TT>??
>>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ... AttributeError: "Manager isn't accessible via Blog instances."
?
檢索所有的對象
?
檢索表中所有數據,最簡單的方式是用all().
?
?
?
?
?
- >>>?all_entries?=?Entry.objects.all()??
>>> all_entries = Entry.objects.all()
?
過濾檢索特定對象
?
檢索過濾特定查詢結果,有兩個方法。
filter(**kwargs) ? 返回一個新的匹配查參數件后的QuerySet?
exclude(**kwargs) 返回一個新的不匹配查詢參數后的QuerySet?
?
例如:
- Entry.objects.filter(pub_date__year= 2006 )??
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 ) ??
- ...?)??
>>> Entry.objects.filter( ... headline__startswith='What' ... ).exclude( ... pub_date__gte=datetime.now() ... ).filter( ... pub_date__gte=datetime(2005, 1, 1) ... )
?
?
過濾結果集是唯一 ?
?
每次你完善一個 QuerySet,你獲得一個全新的結果集,不包括前面的。每次完成的結果集是可以貯存,使用或復用
?
- >>?q1?=?Entry.objects.filter(headline__startswith= "What" ) ??
- >>?q2?=?q1.exclude(pub_date__gte=datetime.now()) ??
- >>?q3?=?q1.filter(pub_date__gte=datetime.now())??
>> 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"單詞開頭的結果集,第二個是第一個的子集,即 pub_date不大于現在的,第三個是第一個的子集 ?, pub_date大于現在的
?
結果集是延遲的 ?
?
QuerySets ?是延遲的,創建 QuerySets ?不會觸及到數據庫動作,你可以多個過濾合并到一起,直到求值的時候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??
>>> q = Entry.objects.filter(headline__startswith="What") >>> q = q.filter(pub_date__lte=datetime.now()) >>> q = q.exclude(body_text__icontains="food") >>> print q
?
雖然看起來執行了三個過濾條件,實際上最后執行 print q的時候,django才開始查詢執行SQL到數據庫。 ?
?
其他的 QuerySet方法
?
大多數情況你使用 all() , filter() ?和 exclude()
限制?QuerySets
使用python的數組限制語法限定QuerySet,如:
取前5個
- <TT? class = "docutils?literal" >>>>?Entry.objects.all()[: 5 ] ??
- </TT>??
>>> Entry.objects.all()[:5]
?
取第五個到第十個
?
?
?
?
- >>>?Entry.objects.all()[ 5 : 10 ]??
>>> Entry.objects.all()[5:10]
?
一般的,限制 QuerySet返回新的 QuerySet,不會立即求值查詢,除非你使用了 "step"參數
?
?
- >>>?Entry.objects.all()[: 10 : 2 ]??
>>> Entry.objects.all()[:10:2]
?
?
?
?
?
?
- >>>?Entry.objects.order_by( 'headline' )[ 0 ] ??
- ??
- >>>?Entry.objects.order_by( 'headline' )[ 0 : 1 ].get()??
>>> Entry.objects.order_by('headline')[0] >>> Entry.objects.order_by('headline')[0:1].get()
?
?
字段查找
?
字段查找是指定SQL語句的WHERE條件從句,通過 QuerySet 的方法 filter() , exclude() 和 get()指定查詢關鍵字
基本查詢 field__lookuptype=value
例如:
- <TT? class = "docutils?literal" >Entry.objects.filter(pub_date__lte= '2006-01-01' )</TT>??
Entry.objects.filter(pub_date__lte='2006-01-01')
?
轉換為SQL:
?
?
?
?
?
?
- SELECT ?*? FROM ?blog_entry? WHERE ?pub_date?<=? '2006-01-01' ;??
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
?
如果你傳了無效的參數會拋異常
?
數據庫API 支持一些查詢類型,下面體驗一下
?
exact
?
- Entry.objects.get(headline__exact= "Man?bites?dog" )??
Entry.objects.get(headline__exact="Man bites dog")
?轉化為SQL:
- SELECT ?...? WHERE ?headline?=? '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 ??
>>> Blog.objects.get(id__exact=14) # Explicit form >>> Blog.objects.get(id=14) # __exact is implied
?
iexact
?
忽略大小寫
- Blog.objects.get(name__iexact= "beatles?blog" )??
Blog.objects.get(name__iexact="beatles blog")
?
blog title會匹配? "Beatles Blog", "beatles blog",?甚至 "BeAtlES blOG".?
?
contains ?
?
包含查詢,區分大小寫
- Entry.objects.get(headline__contains= 'Lennon' )??
Entry.objects.get(headline__contains='Lennon')
?轉化為SQL
- SELECT?...?WHERE?headline?LIKE? '%Lennon%' ;??
SELECT ... WHERE headline LIKE '%Lennon%';
? icontains 不區分大小寫
?
startswith , endswith, istartswith , iendswith
前模糊匹配,后模糊匹配
?
跨關系查詢
?
?
- Entry.objects.filter(blog__name__exact= 'Beatles?Blog' )??
Entry.objects.filter(blog__name__exact='Beatles Blog')
這個可以跨越你想要的深度。
反向跨關系查詢
?
?
- Blog.objects.filter(entry__headline__contains= 'Lennon' )??
Blog.objects.filter(entry__headline__contains='Lennon')
?如果跨越多層關系查詢,中間模型沒有值,django會作為空對待不會發生異常
- Blog.objects.filter(entry__author__name= '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 )??
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' ))??
>>> from django.db.models import F >>> Entry.objects.filter(n_pingbacks__lt=F('n_comments'))
?
django支持加減乘除和模計算
- Entry.objects.filter(n_pingbacks__lt=F( 'n_comments' )?*? 2 )??
Entry.objects.filter(n_pingbacks__lt=F('n_comments') * 2)
?
- Entry.objects.filter(rating__lt=F( 'n_comments' )?+?F( 'n_pingbacks' ))??
Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
?
- Entry.objects.filter(author__name=F( 'blog__name' ))??
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 ??
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 )??
# 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 ??
>>> 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 語句轉義百分號
- Entry.objects.filter(headline__contains= '%' )??
Entry.objects.filter(headline__contains='%')
?轉義為
- SELECT ?...? WHERE ?headline? LIKE ? '%\%%' ;??
SELECT ... WHERE headline LIKE '%\%%';
?
緩存查詢集
?
每個QuerySet都包含一個緩存,以盡量減少對數據庫的訪問。理解他的工作原理很重要,可以寫出最高效的代碼。
在最新創建的QuerySet里,緩存是空的。在第一次 QuerySet 被取值,因此數據庫查詢發生,django把查詢結果放入緩存,并返回給請求,隨后的查詢取值會復用緩存中的結果。
?
保持緩存的思想習慣,因為如果你不正確使用查詢緩存會有麻煩。例如下面例子會創建兩個QuerySet
- >>>? print ?[e.headline? for ?e? in ?Entry.objects.all()] ??
- >>>? print ?[e.pub_date? for ?e? in ?Entry.objects.all()]??
>>> print [e.headline for e in Entry.objects.all()] >>> print [e.pub_date for e in Entry.objects.all()]
?這樣意味著數據庫查詢會執行兩次,實際兩次數據庫加載
為了避免這個問題,簡單保存 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. ??
>>> 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.
?
通過Q對象進行復合查詢
?
關鍵字查詢使用filter 是 and集合,如果你想要執行更多的復合查詢如“or”可以 Q對象。
Q對象( django.db.models.Q )是一個關鍵字集合封裝的參數。
例如
- Q(question__startswith= 'What' )??
Q(question__startswith='What')
?Q對象可以使用 & 和 |鏈接
例如一個OR查詢
- Q(question__startswith= 'Who' )?|?Q(question__startswith= 'What' )??
Q(question__startswith='Who') | Q(question__startswith='What')
?相當于下面的SQL
- WHERE ?question? LIKE ? 'Who%' ? OR ?question? LIKE ? 'What%' ??
WHERE question LIKE 'Who%' OR question LIKE 'What%'
?取消一個Q對象使用~
- Q(question__startswith= 'Who' )?|?~Q(pub_date__year= 2005 )??
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
?可以傳入多個Q對象
- Poll.objects.get( ??
- ????Q(question__startswith= 'Who' ), ??
- ????Q(pub_date=date( 2005 ,? 5 ,? 2 ))?|?Q(pub_date=date( 2005 ,? 5 ,? 6 )) ??
- )??
Poll.objects.get( Q(question__startswith='Who'), Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) )
?翻譯成SQL
- SELECT?*? from ?polls?WHERE?question?LIKE? 'Who%' ??
- ????AND?(pub_date?=? '2005-05-02' ?OR?pub_date?=? '2005-05-06' )??
SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
?
?
比較對象
?
比較兩個模型實例,使用python標準的運算符,兩個等號==
?
- >>>?some_entry?==?other_entry ??
- >>>?some_entry.id?==?other_entry.id ??
- >>>?some_obj?==?other_obj ??
- >>>?some_obj.name?==?other_obj.name??
>>> some_entry == other_entry >>> some_entry.id == other_entry.id >>> some_obj == other_obj >>> some_obj.name == other_obj.name
?
刪除對象
?
刪除方法是很方便的,方法名為 delete(),這個方法直接刪除對象沒有返回值
例如
- e.delete()??
e.delete()
?你也可以批量刪除對象,每個 QuerySet有一個delete()方法,能刪除 QuerySet里所有對象
例如:刪除pub_date為2005年的對象
?
一次修改多個對象
?
有時候你想給 QuerySet里所有對象的一個字段賦予特定值,你可以使用 update()方法
例如
- #?Update?all?the?headlines?with?pub_date?in?2007. ??
- Entry.objects.filter(pub_date__year= 2007 ).update(headline= 'Everything?is?the?same' )??
# Update all the headlines with pub_date in 2007. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
?
這個方法只能用于無關聯字段和外鍵
- >>>?b?=?Blog.objects.get(pk= 1 ) ??
- ??
- #?Change?every?Entry?so?that?it?belongs?to?this?Blog. ??
- >>>?Entry.objects.all().update(blog=b)??
>>> 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方法,如果要執行save,可以如下:
- for ?item? in ?my_queryset: ??
- ????item.save()??
for item in my_queryset: item.save()
?
update也可以使用 F()
?
- #?THIS?WILL?RAISE?A?FieldError ??
- >>>?Entry.objects.update(headline=F( 'blog__name' ))??
# THIS WILL RAISE A FieldError >>> Entry.objects.update(headline=F('blog__name'))
?
關系對象
?
當你在model里定義一個關系時,模型實例會有一個方便的API來訪問關系對象。用本頁上面的模型舉個例子,一個 Entry
對象可以得到blog對象,訪問blog屬性e.blog。
django也創建API來訪問關系對象的另一邊,一個blog對象訪問 Entry 列表 b.entry_set.all() .
?
One-to-many關系
?
如果一個對象有 ForeignKey,這個模型實例訪問關系對象通過簡單的屬性
- >>>?e?=?Entry.objects.get(id= 2 ) ??
- >>>?e.blog? #?Returns?the?related?Blog?object. ??
>>> e = Entry.objects.get(id=2) >>> e.blog # Returns the related Blog object.
?你可以憑借外鍵屬性獲取和賦值,修改外鍵值知道執行save()方法才會保存到數據庫
?
- >>>?e?=?Entry.objects.get(id= 2 ) ??
- >>>?e.blog?=?some_blog ??
- >>>?e.save()??
>>> e = Entry.objects.get(id=2) >>> e.blog = some_blog >>> e.save()
如果 ForeignKey ? 設置了null=True 你可以賦值為None
?
- >>>?e?=?Entry.objects.get(id= 2 ) ??
- >>>?e.blog?=? None ??
- >>>?e.save()? #?"UPDATE?blog_entry?SET?blog_id?=?NULL?...;" ??
>>> e = Entry.objects.get(id=2) >>> e.blog = None >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
?
- >>>?e?=?Entry.objects.get(id= 2 ) ??
- >>>? print ?e.blog?? #?Hits?the?database?to?retrieve?the?associated?Blog. ??
- >>>? print ?e.blog?? #?不會在向數據庫取;?使用緩存中的值. ??
>>> e = Entry.objects.get(id=2) >>> print e.blog # Hits the database to retrieve the associated Blog. >>> print e.blog # 不會在向數據庫取; 使用緩存中的值.
?
- >>>?e?=?Entry.objects.select_related().get(id= 2 ) ??
- >>>? print ?e.blog?? #?不會在向數據庫取;?使用緩存中的值. ??
- >>>? print ?e.blog?? #?不會在向數據庫取;?使用緩存中的值. ??
>>> e = Entry.objects.select_related().get(id=2) >>> print e.blog # 不會在向數據庫取; 使用緩存中的值. >>> print e.blog # 不會在向數據庫取; 使用緩存中的值.
?
- >>>?b?=?Blog.objects.get(id= 1 ) ??
- >>>?b.entry_set.all()? #?返回所有blog的關聯對象. ??
- ??
- #?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的關聯對象 ??
- ??
- #?b.entries?is?a?Manager?that?returns?QuerySets. ??
- >>>?b.entries.filter(headline__contains= 'Lennon' ) ??
- >>>?b.entries.count()??
>>> b = Blog.objects.get(id=1) >>> b.entry_set.all() # 返回所有blog的關聯對象. # 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的關聯對象 # b.entries is a Manager that returns QuerySets. >>> b.entries.filter(headline__contains='Lennon') >>> b.entries.count()
?
add(obj1, obj2, ...) 增加多個關系對象
create(**kwargs) 建立新對象
remove(obj1, obj2, ...) 去除多個關系對象
clear() 清理所有關系對象
?
- b?=?Blog.objects.get(id= 1 ) ??
- b.entry_set?=?[e1,?e2]??
b = Blog.objects.get(id=1) b.entry_set = [e1, e2]
?
Many-to-many關系
- 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?. ??
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 .
?
One-to-one關系
?
- class ?EntryDetail(models.Model): ??
- ????entry?=?models.OneToOneField(Entry) ??
- ????details?=?models.TextField() ??
- ??
- ed?=?EntryDetail.objects.get(id= 2 ) ??
- ed.entry? #?返回?Entry?對象. ??
?
?
三、檢索對象
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
??? ...
AttributeError: "Manager isn't accessible via Blog instances."
1、檢索所有的對象
>>> all_entries = Entry.objects.all()
使用all()方法返回數據庫中的所有對象。
2、檢索特定的對象
使用以下兩個方法:
fileter(**kwargs)
返回一個與參數匹配的QuerySet,相當于等于(=).
exclude(**kwargs)
返回一個與參數不匹配的QuerySet,相當于不等于(!=)。
Entry.objects.filter(pub_date__year=2006)
不使用Entry.objects.all().filter(pub_date__year=2006),雖然也能運行,all()最好再獲取所有的對象時使用。
上面的例子等同于的sql語句:
slect * from entry where 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是headline like 'What%' and put_date<now() and pub_date>2005-01-01
另外一種方法:
>> q1 = Entry.objects.filter(headline__startswith="What")
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
