日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

第四天

系統(tǒng) 1849 0

真想抽死自己。

python manage.py shell

這句話,決定可以將環(huán)境變量,也就是sys.path的環(huán)境變量值給你。而不是python的編譯環(huán)境

/////////////////////////////////////////////下面弄了點(diǎn)翻譯/////////////////////////////////////////

?

生成查詢

?

你創(chuàng)建完數(shù)據(jù)模型,django會(huì)自動(dòng)提供給你數(shù)據(jù)庫抽象的API,可以創(chuàng)建,獲取,修改,刪除對象.本篇文檔講解如何使用API。

?

我們參考下面模型,一個(gè)weblog:

Python代碼 復(fù)制代碼
  1. class ?Blog(models.Model): ??
  2. ????name?=?models.CharField(max_length= 100 ) ??
  3. ????tagline?=?models.TextField() ??
  4. ??
  5. ???? def ?__unicode__( self ): ??
  6. ???????? return ? self .name ??
  7. ??
  8. class ?Author(models.Model): ??
  9. ????name?=?models.CharField(max_length= 50 ) ??
  10. ????email?=?models.EmailField() ??
  11. ??
  12. ???? def ?__unicode__( self ): ??
  13. ???????? return ? self .name ??
  14. ??
  15. class ?Entry(models.Model): ??
  16. ????blog?=?models.ForeignKey(Blog) ??
  17. ????headline?=?models.CharField(max_length= 255 ) ??
  18. ????body_text?=?models.TextField() ??
  19. ????pub_date?=?models.DateTimeField() ??
  20. ????authors?=?models.ManyToManyField(Author) ??
  21. ????n_comments?=?models.IntegerField() ??
  22. ????n_pingbacks?=?models.IntegerField() ??
  23. ????rating?=?models.IntegerField() ??
  24. ??
  25. ???? def ?__unicode__( self ): ??
  26. ???????? 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

  

?

創(chuàng)建對象

?

用python對象描述數(shù)據(jù)庫表的數(shù)據(jù),django使用一個(gè)直觀的系統(tǒng),一個(gè)模型類描述一個(gè)數(shù)據(jù)表,一個(gè)類的實(shí)例描述表的一條詳細(xì)記錄。使用模型的save()方法將對象創(chuàng)建到數(shù)據(jù)庫。

Python代碼 復(fù)制代碼
  1. >>>? from ?mysite.blog.models? import ?Blog ??
  2. >>>?b?=?Blog(name= 'Beatles?Blog' ,?tagline= 'All?the?latest?Beatles?news.' ) ??
  3. >>>?b.save()??
    >>> from mysite.blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()

  

?只有執(zhí)行save方法時(shí),django才會(huì)執(zhí)行sql把對象寫入數(shù)據(jù)庫。

?

保存修改的對象

?

保存修改仍然使用save()方法

Python代碼 復(fù)制代碼
  1. >>?b5.name?=? 'New?name' ??
  2. >>?b5.save()??
    >> b5.name = 'New name'
>> b5.save()
  

?

保存 ForeignKey 和 ManyToManyField 字段

?

Python代碼 復(fù)制代碼
  1. >>>?cheese_blog?=?Blog.objects.get(name= "Cheddar?Talk" ) ??
  2. >>>?entry.blog?=?cheese_blog ??
  3. >>>?entry.save()??
    >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()

  

ManyToManyField 增加記錄

?

Python代碼 復(fù)制代碼
  1. >>?joe?=?Author.objects.create(name= "Joe" ) ??
  2. >>?entry.authors.add(joe)??
    >> joe = Author.objects.create(name="Joe")
>> entry.authors.add(joe)
  

?

檢索對象

?

從數(shù)據(jù)庫里檢索對象?,可以通過模型的Manage來建立QuerySet,一個(gè)queryset表現(xiàn)為一個(gè)數(shù)據(jù)庫中對象的結(jié)合,他可以有0個(gè)一個(gè)或多個(gè)過濾條件,在SQL里QUERYSET相當(dāng)于SELECT 語句用 WHERE ?或 LIMIT過濾。

你通過模型的manager來獲取QUERYSET,每個(gè)模型至少有一個(gè)manager

Python代碼 復(fù)制代碼
  1. <TT? class = "docutils?literal" >>>>?Blog.objects ??
  2. <django.db.models.manager.Manager?object?at?...> ??
  3. >>>?b?=?Blog(name= 'Foo' ,?tagline= 'Bar' ) ??
  4. >>>?b.objects ??
  5. Traceback: ??
  6. ????... ??
  7. AttributeError:? "Manager?isn't?accessible?via?Blog?instances." ??
  8. </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."

    
  

?

檢索所有的對象

?

檢索表中所有數(shù)據(jù),最簡單的方式是用all().

?

?

?

?

?

Python代碼 復(fù)制代碼
  1. >>>?all_entries?=?Entry.objects.all()??
    >>> all_entries = Entry.objects.all()

  

?

過濾檢索特定對象

?

檢索過濾特定查詢結(jié)果,有兩個(gè)方法。

filter(**kwargs) ? 返回一個(gè)新的匹配查參數(shù)件后的QuerySet?

exclude(**kwargs) 返回一個(gè)新的不匹配查詢參數(shù)后的QuerySet?

?

例如:

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(pub_date__year= 2006 )??
    Entry.objects.filter(pub_date__year=2006)

  

?

?

鏈接過濾

?

Python代碼 復(fù)制代碼
  1. >>>?Entry.objects.filter( ??
  2. ...?????headline__startswith= 'What' ??
  3. ...?).exclude( ??
  4. ...?????pub_date__gte=datetime.now() ??
  5. ...?).filter( ??
  6. ...?????pub_date__gte=datetime( 2005 ,? 1 ,? 1 ) ??
  7. ...?)??
    >>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.now()
... ).filter(
...     pub_date__gte=datetime(2005, 1, 1)
... )

  

?

?

過濾結(jié)果集是唯一 ?

?

每次你完善一個(gè) QuerySet,你獲得一個(gè)全新的結(jié)果集,不包括前面的。每次完成的結(jié)果集是可以貯存,使用或復(fù)用

?

Python代碼 復(fù)制代碼
  1. >>?q1?=?Entry.objects.filter(headline__startswith= "What" ) ??
  2. >>?q2?=?q1.exclude(pub_date__gte=datetime.now()) ??
  3. >>?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())
  

?

三個(gè) QuerySets ?是分開的,第一個(gè)是headline以"What"單詞開頭的結(jié)果集,第二個(gè)是第一個(gè)的子集,即 pub_date不大于現(xiàn)在的,第三個(gè)是第一個(gè)的子集 ?, pub_date大于現(xiàn)在的

?

結(jié)果集是延遲的 ?

?

QuerySets ?是延遲的,創(chuàng)建 QuerySets ?不會(huì)觸及到數(shù)據(jù)庫動(dòng)作,你可以多個(gè)過濾合并到一起,直到求值的時(shí)候django才會(huì)開始查詢。如:

Python代碼 復(fù)制代碼
  1. >>>?q?=?Entry.objects.filter(headline__startswith= "What" ) ??
  2. >>>?q?=?q.filter(pub_date__lte=datetime.now()) ??
  3. >>>?q?=?q.exclude(body_text__icontains= "food" ) ??
  4. >>>? 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

  

?

雖然看起來執(zhí)行了三個(gè)過濾條件,實(shí)際上最后執(zhí)行 print q的時(shí)候,django才開始查詢執(zhí)行SQL到數(shù)據(jù)庫。 ?

?

其他的 QuerySet方法

?

大多數(shù)情況你使用 all() , filter() ?和 exclude()

限制?QuerySets

使用python的數(shù)組限制語法限定QuerySet,如:

取前5個(gè)

Python代碼 復(fù)制代碼
  1. <TT? class = "docutils?literal" >>>>?Entry.objects.all()[: 5 ] ??
  2. </TT>??
    
      >>> Entry.objects.all()[:5]

    
  

?

取第五個(gè)到第十個(gè)

?

?

?

?

Python代碼 復(fù)制代碼
  1. >>>?Entry.objects.all()[ 5 : 10 ]??
    >>> Entry.objects.all()[5:10]

  

?

一般的,限制 QuerySet返回新的 QuerySet,不會(huì)立即求值查詢,除非你使用了 "step"參數(shù)

?

?

Python代碼 復(fù)制代碼
  1. >>>?Entry.objects.all()[: 10 : 2 ]??
    >>> Entry.objects.all()[:10:2]

  

?

?

?

?

?

?

Python代碼 復(fù)制代碼
  1. >>>?Entry.objects.order_by( 'headline' )[ 0 ] ??
  2. ??
  3. >>>?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()指定查詢關(guān)鍵字

基本查詢 field__lookuptype=value

例如:

Python代碼 復(fù)制代碼
  1. <TT? class = "docutils?literal" >Entry.objects.filter(pub_date__lte= '2006-01-01' )</TT>??
    
      Entry.objects.filter(pub_date__lte='2006-01-01')
    
  

?

轉(zhuǎn)換為SQL:

?

?

?

?

?

?

Sql代碼 復(fù)制代碼
  1. SELECT ?*? FROM ?blog_entry? WHERE ?pub_date?<=? '2006-01-01' ;??
    SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
  

?

如果你傳了無效的參數(shù)會(huì)拋異常

?

數(shù)據(jù)庫API 支持一些查詢類型,下面體驗(yàn)一下

?

exact

?

Python代碼 復(fù)制代碼
  1. Entry.objects.get(headline__exact= "Man?bites?dog" )??
    Entry.objects.get(headline__exact="Man bites dog")

  

?轉(zhuǎn)化為SQL:

Sql代碼 復(fù)制代碼
  1. SELECT ?...? WHERE ?headline?=? 'Man?bites?dog' ;??
    SELECT ... WHERE headline = 'Man bites dog';

  

?

?

如果查詢沒有提供雙下劃線,那么會(huì)默認(rèn)?__exact=

Python代碼 復(fù)制代碼
  1. >>>?Blog.objects.get(id__exact= 14 )?? #?Explicit?form ??
  2. >>>?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

?

忽略大小寫

Python代碼 復(fù)制代碼
  1. Blog.objects.get(name__iexact= "beatles?blog" )??
    Blog.objects.get(name__iexact="beatles blog")

  

?

blog title會(huì)匹配? "Beatles Blog", "beatles blog",?甚至 "BeAtlES blOG".?

?

contains ?

?

包含查詢,區(qū)分大小寫

Python代碼 復(fù)制代碼
  1. Entry.objects.get(headline__contains= 'Lennon' )??
    Entry.objects.get(headline__contains='Lennon')
  

?轉(zhuǎn)化為SQL

Python代碼 復(fù)制代碼
  1. SELECT?...?WHERE?headline?LIKE? '%Lennon%' ;??
    SELECT ... WHERE headline LIKE '%Lennon%';
  

? icontains 不區(qū)分大小寫

?

startswith , endswith, istartswith iendswith

前模糊匹配,后模糊匹配

?

跨關(guān)系查詢

?

?

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(blog__name__exact= 'Beatles?Blog' )??
    Entry.objects.filter(blog__name__exact='Beatles Blog')
  

這個(gè)可以跨越你想要的深度。

反向跨關(guān)系查詢

?

?

Python代碼 復(fù)制代碼
  1. Blog.objects.filter(entry__headline__contains= 'Lennon' )??
    Blog.objects.filter(entry__headline__contains='Lennon')
  

?如果跨越多層關(guān)系查詢,中間模型沒有值,django會(huì)作為空對待不會(huì)發(fā)生異常

Python代碼 復(fù)制代碼
  1. Blog.objects.filter(entry__author__name= 'Lennon' ??
    Blog.objects.filter(entry__author__name='Lennon'
  

?

Python代碼 復(fù)制代碼
  1. Blog.objects.filter(entry__author__name__isnull= True ) ??
  2. ??
  3. Blog.objects.filter(entry__author__isnull= False , ??
  4. ????????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)
  

?

過濾器可參考模型字段

?

目前給的例子里,我們建立了過濾,比照模型字段值和一個(gè)固定的值,但是如果我們想比較同一個(gè)模型里的一個(gè)指端和另一個(gè)字段的值,django提供 F()

?

Python代碼 復(fù)制代碼
  1. >>>? from ?django.db.models? import ?F ??
  2. >>>?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支持加減乘除和模計(jì)算

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(n_pingbacks__lt=F( 'n_comments' )?*? 2 )??
    Entry.objects.filter(n_pingbacks__lt=F('n_comments') * 2)

  

?

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(rating__lt=F( 'n_comments' )?+?F( 'n_pingbacks' ))??
    Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))

  

?

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(author__name=F( 'blog__name' ))??
    Entry.objects.filter(author__name=F('blog__name'))
  

?

主鍵查詢捷徑

?

Python代碼 復(fù)制代碼
  1. Blog.objects.get(id__exact= 14 )? #?Explicit?form ??
  2. Blog.objects.get(id= 14 )? #?__exact?is?implied ??
  3. 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 查詢

Python代碼 復(fù)制代碼
  1. #?Get?blogs?entries?with?id?1,?4?and?7 ??
  2. >>>?Blog.objects.filter(pk__in=[ 1 , 4 , 7 ]) ??
  3. ??
  4. #?Get?all?blog?entries?with?id?>?14 ??
  5. >>>?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)
  

?跨越查詢

Python代碼 復(fù)制代碼
  1. >>>?Entry.objects.filter(blog__id__exact= 3 )? #?Explicit?form ??
  2. >>>?Entry.objects.filter(blog__id= 3 )???????? #?__exact?is?implied ??
  3. >>>?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 語句轉(zhuǎn)義百分號(hào)

Python代碼 復(fù)制代碼
  1. Entry.objects.filter(headline__contains= '%' )??
    Entry.objects.filter(headline__contains='%')

  

?轉(zhuǎn)義為

Sql代碼 復(fù)制代碼
  1. SELECT ?...? WHERE ?headline? LIKE ? '%\%%' ;??
    SELECT ... WHERE headline LIKE '%\%%';

  

?

緩存查詢集

?

每個(gè)QuerySet都包含一個(gè)緩存,以盡量減少對數(shù)據(jù)庫的訪問。理解他的工作原理很重要,可以寫出最高效的代碼。

在最新創(chuàng)建的QuerySet里,緩存是空的。在第一次 QuerySet 被取值,因此數(shù)據(jù)庫查詢發(fā)生,django把查詢結(jié)果放入緩存,并返回給請求,隨后的查詢?nèi)≈禃?huì)復(fù)用緩存中的結(jié)果。

?

保持緩存的思想習(xí)慣,因?yàn)槿绻悴徽_使用查詢緩存會(huì)有麻煩。例如下面例子會(huì)創(chuàng)建兩個(gè)QuerySet

Python代碼 復(fù)制代碼
  1. >>>? print ?[e.headline? for ?e? in ?Entry.objects.all()] ??
  2. >>>? 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()]

  

?這樣意味著數(shù)據(jù)庫查詢會(huì)執(zhí)行兩次,實(shí)際兩次數(shù)據(jù)庫加載

為了避免這個(gè)問題,簡單保存 QuerySet 復(fù)用

Python代碼 復(fù)制代碼
  1. >>>?queryset?=?Poll.objects.all() ??
  2. >>>? print ?[p.headline? for ?p? in ?queryset]? #?Evaluate?the?query?set. ??
  3. >>>? 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對象進(jìn)行復(fù)合查詢

?

關(guān)鍵字查詢使用filter 是 and集合,如果你想要執(zhí)行更多的復(fù)合查詢?nèi)纭皁r”可以 Q對象。

Q對象( django.db.models.Q )是一個(gè)關(guān)鍵字集合封裝的參數(shù)。

例如

Python代碼 復(fù)制代碼
  1. Q(question__startswith= 'What' )??
    Q(question__startswith='What')

  

?Q對象可以使用 & |鏈接

例如一個(gè)OR查詢

Python代碼 復(fù)制代碼
  1. Q(question__startswith= 'Who' )?|?Q(question__startswith= 'What' )??
    Q(question__startswith='Who') | Q(question__startswith='What')

  

?相當(dāng)于下面的SQL

Sql代碼 復(fù)制代碼
  1. WHERE ?question? LIKE ? 'Who%' ? OR ?question? LIKE ? 'What%' ??
    WHERE question LIKE 'Who%' OR question LIKE 'What%'
  

?取消一個(gè)Q對象使用~

Python代碼 復(fù)制代碼
  1. Q(question__startswith= 'Who' )?|?~Q(pub_date__year= 2005 )??
    Q(question__startswith='Who') | ~Q(pub_date__year=2005)

  

?可以傳入多個(gè)Q對象

Python代碼 復(fù)制代碼
  1. Poll.objects.get( ??
  2. ????Q(question__startswith= 'Who' ), ??
  3. ????Q(pub_date=date( 2005 ,? 5 ,? 2 ))?|?Q(pub_date=date( 2005 ,? 5 ,? 6 )) ??
  4. )??
    Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

  

?翻譯成SQL

Python代碼 復(fù)制代碼
  1. SELECT?*? from ?polls?WHERE?question?LIKE? 'Who%' ??
  2. ????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')
  

?

?

比較對象

?

比較兩個(gè)模型實(shí)例,使用python標(biāo)準(zhǔn)的運(yùn)算符,兩個(gè)等號(hào)==

?

Python代碼 復(fù)制代碼
  1. >>>?some_entry?==?other_entry ??
  2. >>>?some_entry.id?==?other_entry.id ??
  3. >>>?some_obj?==?other_obj ??
  4. >>>?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(),這個(gè)方法直接刪除對象沒有返回值

例如

Python代碼 復(fù)制代碼
  1. e.delete()??
    e.delete()

  

?你也可以批量刪除對象,每個(gè) QuerySet有一個(gè)delete()方法,能刪除 QuerySet里所有對象

例如:刪除pub_date為2005年的對象

?

一次修改多個(gè)對象

?

有時(shí)候你想給 QuerySet里所有對象的一個(gè)字段賦予特定值,你可以使用 update()方法

例如

Python代碼 復(fù)制代碼
  1. #?Update?all?the?headlines?with?pub_date?in?2007. ??
  2. 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')

  

?

這個(gè)方法只能用于無關(guān)聯(lián)字段和外鍵

Python代碼 復(fù)制代碼
  1. >>>?b?=?Blog.objects.get(pk= 1 ) ??
  2. ??
  3. #?Change?every?Entry?so?that?it?belongs?to?this?Blog. ??
  4. >>>?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方法,如果要執(zhí)行save,可以如下:

Python代碼 復(fù)制代碼
  1. for ?item? in ?my_queryset: ??
  2. ????item.save()??
    for item in my_queryset:
    item.save()

  

?

update也可以使用 F()

?

Python代碼 復(fù)制代碼
  1. #?THIS?WILL?RAISE?A?FieldError ??
  2. >>>?Entry.objects.update(headline=F( 'blog__name' ))??
    # THIS WILL RAISE A FieldError
>>> Entry.objects.update(headline=F('blog__name'))
  

?

關(guān)系對象

?

當(dāng)你在model里定義一個(gè)關(guān)系時(shí),模型實(shí)例會(huì)有一個(gè)方便的API來訪問關(guān)系對象。用本頁上面的模型舉個(gè)例子,一個(gè) Entry

對象可以得到blog對象,訪問blog屬性e.blog。

django也創(chuàng)建API來訪問關(guān)系對象的另一邊,一個(gè)blog對象訪問 Entry 列表 b.entry_set.all() .

?

One-to-many關(guān)系

?

如果一個(gè)對象有 ForeignKey,這個(gè)模型實(shí)例訪問關(guān)系對象通過簡單的屬性

Python代碼 復(fù)制代碼
  1. >>>?e?=?Entry.objects.get(id= 2 ) ??
  2. >>>?e.blog? #?Returns?the?related?Blog?object. ??
    >>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.

  

?你可以憑借外鍵屬性獲取和賦值,修改外鍵值知道執(zhí)行save()方法才會(huì)保存到數(shù)據(jù)庫

?

Python代碼 復(fù)制代碼
  1. >>>?e?=?Entry.objects.get(id= 2 ) ??
  2. >>>?e.blog?=?some_blog ??
  3. >>>?e.save()??
    >>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()

  

如果 ForeignKey ? 設(shè)置了null=True 你可以賦值為None

?

Python代碼 復(fù)制代碼
  1. >>>?e?=?Entry.objects.get(id= 2 ) ??
  2. >>>?e.blog?=? None ??
  3. >>>?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 ...;"

  

?

Python代碼 復(fù)制代碼
  1. >>>?e?=?Entry.objects.get(id= 2 ) ??
  2. >>>? print ?e.blog?? #?Hits?the?database?to?retrieve?the?associated?Blog. ??
  3. >>>? print ?e.blog?? #?不會(huì)在向數(shù)據(jù)庫取;?使用緩存中的值. ??
    >>> e = Entry.objects.get(id=2)
>>> print e.blog  # Hits the database to retrieve the associated Blog.
>>> print e.blog  # 不會(huì)在向數(shù)據(jù)庫取; 使用緩存中的值.

  

?

Python代碼 復(fù)制代碼
  1. >>>?e?=?Entry.objects.select_related().get(id= 2 ) ??
  2. >>>? print ?e.blog?? #?不會(huì)在向數(shù)據(jù)庫取;?使用緩存中的值. ??
  3. >>>? print ?e.blog?? #?不會(huì)在向數(shù)據(jù)庫取;?使用緩存中的值. ??
    >>> e = Entry.objects.select_related().get(id=2)
>>> print e.blog  # 不會(huì)在向數(shù)據(jù)庫取; 使用緩存中的值.
>>> print e.blog  # 不會(huì)在向數(shù)據(jù)庫取; 使用緩存中的值.

  

?

Python代碼 復(fù)制代碼
  1. >>>?b?=?Blog.objects.get(id= 1 ) ??
  2. >>>?b.entry_set.all()? #?返回所有blog的關(guān)聯(lián)對象. ??
  3. ??
  4. #?b.entry_set?is?a?Manager?that?returns?QuerySets. ??
  5. >>>?b.entry_set.filter(headline__contains= 'Lennon' ) ??
  6. >>>?b.entry_set.count() ??
  7. ??
  8. ??
  9. >>>?b?=?Blog.objects.get(id= 1 ) ??
  10. >>>?b.entries.all()? #?返回所有blog的關(guān)聯(lián)對象 ??
  11. ??
  12. #?b.entries?is?a?Manager?that?returns?QuerySets. ??
  13. >>>?b.entries.filter(headline__contains= 'Lennon' ) ??
  14. >>>?b.entries.count()??
    >>> 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, ...) 增加多個(gè)關(guān)系對象

create(**kwargs) 建立新對象

remove(obj1, obj2, ...) 去除多個(gè)關(guān)系對象

clear() 清理所有關(guān)系對象

?

Python代碼 復(fù)制代碼
  1. b?=?Blog.objects.get(id= 1 ) ??
  2. b.entry_set?=?[e1,?e2]??
    b = Blog.objects.get(id=1)
b.entry_set = [e1, e2]

  

?

Many-to-many關(guān)系

Python代碼 復(fù)制代碼
  1. e?=?Entry.objects.get(id= 3 ) ??
  2. e.authors.all()? #?返回Entry所有authors?. ??
  3. e.authors.count() ??
  4. e.authors.filter(name__contains= 'John' ) ??
  5. ??
  6. a?=?Author.objects.get(id= 5 ) ??
  7. 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關(guān)系

?

Python代碼 復(fù)制代碼
  1. class ?EntryDetail(models.Model): ??
  2. ????entry?=?models.OneToOneField(Entry) ??
  3. ????details?=?models.TextField() ??
  4. ??
  5. ed?=?EntryDetail.objects.get(id= 2 ) ??
  6. 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()方法返回?cái)?shù)據(jù)庫中的所有對象。

2、檢索特定的對象
使用以下兩個(gè)方法:
fileter(**kwargs)
返回一個(gè)與參數(shù)匹配的QuerySet,相當(dāng)于等于(=).
exclude(**kwargs)
返回一個(gè)與參數(shù)不匹配的QuerySet,相當(dāng)于不等于(!=)。

Entry.objects.filter(pub_date__year=2006)
不使用Entry.objects.all().filter(pub_date__year=2006),雖然也能運(yùn)行,all()最好再獲取所有的對象時(shí)使用。
上面的例子等同于的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")

第四天


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會(huì)非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 周宁县| 潞西市| 广灵县| 子长县| 白沙| 哈密市| 云安县| 镇原县| 拜泉县| 浦江县| 安溪县| 东阿县| 慈利县| 临清市| 会理县| 宜宾县| 兖州市| 孝义市| 合水县| 莱州市| 沁源县| 陕西省| 萨迦县| 郧西县| 延津县| 毕节市| 翼城县| 延寿县| 闵行区| 合阳县| 柳江县| 沙田区| 台东县| 余姚市| 汾阳市| 南京市| 谢通门县| 桦南县| 资兴市| 武陟县| 金坛市|