天天看點

【轉】django的ORM操作資料庫樣例

這個算是我看到的大全了,希望可以解決明天我希望解決的兩個問題。。。

【轉】django的ORM操作資料庫樣例
【轉】django的ORM操作資料庫樣例

這是model,有blog,author,以及entry;其中entry分别與blog與author表關聯,entry與blog表是通過外鍵(models.foreignkey())相連,屬于一對多的關系,即一個entry對應多個blog,entry與author是多對多的關系,通過modles.manytomanyfield()實作。 

一、插入資料庫,用save()方法實作,如下: 

>>> from mysite.blog.models import blog 

>>> b = blog(name='beatles blog', tagline='all the latest beatles news.') 

>>> b.save() 

二、更新資料庫,也用save()方法實作,如下: 

>> b5.name = 'new name' 

>> b5.save() 

儲存外鍵和多對多關系的字段,如下例子: 

更新外鍵字段和普通的字段一樣,隻要指定一個對象的正确類型。 

>>> cheese_blog = blog.objects.get(name="cheddar talk") 

>>> entry.blog = cheese_blog 

>>> entry.save() 

更新多對多字段時又一點不太一樣,使用add()方法添加相關聯的字段的值。 

>> joe = author.objects.create(name="joe") 

>> entry.authors.add(joe) 

三、檢索對象 

>>> 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") 

>> q2 = q1.exclude(pub_date__gte=datetime.now()) 

>> q3 = q1.filter(pub_date__gte=datetime.now()) 

這種方法的好處是可以對q1進行重用。 

queryset是延遲加載 

隻在使用的時候才會去通路資料庫,如下: 

>>> 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時才會通路資料庫。 

其他的queryset方法 

>>> entry.objects.all()[:5] 

這是查找前5個entry表裡的資料 

>>> entry.objects.all()[5:10] 

這是查找從第5個到第10個之間的資料。 

>>> entry.objects.all()[:10:2] 

這是查詢從第0個開始到第10個,步長為2的資料。 

>>> entry.objects.order_by('headline')[0] 

這是取按headline字段排序後的第一個對象。 

>>> entry.objects.order_by('headline')[0:1].get() 

這和上面的等同的。 

>>> entry.objects.filter(pub_date__lte='2006-01-01') 

等同于select * from blog_entry where pub_date <= '2006-01-01'; 

>>> entry.objects.get(headline__exact="man bites dog") 

等同于select ... where headline = 'man bites dog'; 

>>> blog.objects.get(id__exact=14)  # explicit form 

>>> blog.objects.get(id=14)         # __exact is implied 

這兩種方式是等同的,都是查找id=14的對象。 

>>> blog.objects.get(name__iexact="beatles blog") 

查找name="beatles blog"的對象,不去飯大小寫。 

entry.objects.get(headline__contains='lennon') 

等同于select ... where headline like '%lennon%'; 

startswith 等同于sql語句中的 name like 'lennon%', 

endswith等同于sql語句中的 name like '%lennon'. 

>>> entry.objects.filter(blog__name__exact='beatles blog') 

查找entry表中外鍵關系blog_name='beatles blog'的entry對象。 

>>> blog.objects.filter(entry__headline__contains='lennon') 

查找blog表中外鍵關系entry表中的headline字段中包含lennon的blog資料。 

blog.objects.filter(entry__author__name='lennon') 

查找blog表中外鍵關系entry表中的author字段中包含lennon的blog資料。 

blog.objects.filter(entry__author__name__isnull=true) 

blog.objects.filter(entry__author__isnull=false,entry__author__name__isnull=true) 

查詢的是author_name為null的值 

blog.objects.filter(entry__headline__contains='lennon',entry__pub_date__year=2008) 

blog.objects.filter(entry__headline__contains='lennon').filter(  entry__pub_date__year=2008) 

這兩種查詢在某些情況下是相同的,某些情況下是不同的。第一種是限制所有的blog資料的,而第二種情況則是第一個filter是 

限制blog的,而第二個filter則是限制entry的 

>>> 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 

等同于select * from where id=14 

# get blogs entries with id 1, 4 and 7 

>>> blog.objects.filter(pk__in=[1,4,7]) 

等同于select * from where id in{1,4,7} 

# get all blog entries with id > 14 

>>> blog.objects.filter(pk__gt=14) 

等同于select * from id>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(headline__contains='%') 

等同于select ... where headline like '%\%%'; 

caching and querysets 

>>> print [e.headline for e in entry.objects.all()] 

>>> print [e.pub_date for e in entry.objects.all()] 

應改寫為: 

>> 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對象實作複雜的查詢 

q(question__startswith='who') | q(question__startswith='what') 

等同于where question like 'who%' or question like 'what%' 

poll.objects.get( 

    q(question__startswith='who'), 

    q(pub_date=date(2005, 5, 2)) | q(pub_date=date(2005, 5, 6)) 

等同于select * from polls where question like 'who%' and (pub_date = '2005-05-02' or pub_date = '2005-05-06') 

    q(pub_date=date(2005, 5, 2)) | q(pub_date=date(2005, 5, 6)), 

    question__startswith='who') 

等同于poll.objects.get(question__startswith='who', q(pub_date=date(2005, 5, 2)) | q(pub_date=date(2005, 5, 6))) 

五、比較對象 

>>> some_entry == other_entry 

>>> some_entry.id == other_entry.id 

六、删除 

entry.objects.filter(pub_date__year=2005).delete() 

b = blog.objects.get(pk=1) 

# this will delete the blog and all of its entry objects. 

b.delete() 

entry.objects.all().delete() 

删除所有 

七、一次更新多個值 

# 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) 

如果用save()方法,必須一個一個進行儲存,需要對其就行周遊,如下: 

for item in my_queryset: 

    item.save() 

關聯對象 

one-to-many 

>>> e = entry.objects.get(id=2) 

>>> e.blog # returns the related blog object. 

>>> e.blog = some_blog 

>>> e.save() 

>>> e.blog = none 

>>> e.save() # "update blog_entry set blog_id = null ...;" 

>>> print e.blog  # hits the database to retrieve the associated blog. 

>>> print e.blog  # doesn't hit the database; uses cached version. 

>>> e = entry.objects.select_related().get(id=2) 

>>> print e.blog  # doesn't hit the database; uses cached version 

>>> b = blog.objects.get(id=1) 

>>> b.entry_set.all() # returns all entry objects related to blog. 

# b.entry_set is a manager that returns querysets. 

>>> b.entry_set.filter(headline__contains='lennon') 

>>> b.entry_set.count() 

>>> b.entries.all() # returns all entry objects related to blog. 

# b.entries is a manager that returns querysets. 

>>> b.entries.filter(headline__contains='lennon') 

>>> b.entries.count() 

you cannot access a reverse foreignkey manager from the class; it must be accessed from an instance: 

>>> blog.entry_set 

add(obj1, obj2, ...) 

    adds the specified model objects to the related object set. 

create(**kwargs) 

    creates a new object, saves it and puts it in the related object set. returns the newly created object. 

remove(obj1, obj2, ...) 

    removes the specified model objects from the related object set. 

clear() 

    removes all objects from the related object set. 

many-to-many類型: 

e = entry.objects.get(id=3) 

e.authors.all() # returns all author objects for this entry. 

e.authors.count() 

e.authors.filter(name__contains='john') 

a = author.objects.get(id=5) 

a.entry_set.all() # returns all entry objects for this author. 

one-to-one 類型: 

class entrydetail(models.model): 

    entry = models.onetoonefield(entry) 

    details = models.textfield() 

ed = entrydetail.objects.get(id=2) 

ed.entry # returns the related entry object 

使用sql語句進行查詢: 

def my_custom_sql(self): 

    from django.db import connection 

    cursor = connection.cursor() 

    cursor.execute("select foo from bar where baz = %s", [self.baz]) 

    row = cursor.fetchone() 

    return row