閱讀博客http://blog.jobbole.com/74881/的筆記python
在數據庫有外鍵的時候,使用select_related()和prefetch_related()能夠很好的減小數據庫請求的次數,從而提升性能.數據庫
下面是數據庫設計圖django
models.py以下:緩存
from django.db import models class Province(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name class City(models.Model): name = models.CharField(max_length=5) province = models.ForeignKey(Province) def __unicode__(self): return self.name class Person(models.Model): firstname = models.CharField(max_length=10) lastname = models.CharField(max_length=10) visitation = models.ManyToManyField(City, related_name = "visitor") hometown = models.ForeignKey(City, related_name = "birth") living = models.ForeignKey(City, related_name = "citizen") def __unicode__(self): return self.firstname + self.lastname
app名爲"QSOptimize"app
`qsoptimize_province` 表中只有2條數據:湖北省和廣東省,`qsoptimize_city`表中只有三條數據:武漢市、十堰市和廣州市數據庫設計
select_related()函數
對於一對一字段(OneToOneField)和外鍵字段(ForeignKey),可使用select_related()來對QuerySet進行優化.性能
在對QuerySet使用select_related()函數後,Django會獲取相應外鍵對應的對象,從而在以後須要的時候沒必要再查詢數據庫了。fetch
一個例子:優化
>>> citys = City.objects.all() >>> for c in citys: ... print c.province
這樣會致使線性的SQL查詢,SQL查詢語句以下:
SELECT `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id` FROM `QSOptimize_city` SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` = 1 ; SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` = 2 ; SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` = 1 ;
使用select_related()函數後
>>> citys = City.objects.select_related().all() >>> for c in citys: ... print c.province
就只有一次SQL查詢,大大減小SQL查詢次數
SELECT `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id`, `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM`QSOptimize_city` INNER JOIN `QSOptimize_province` ON (`QSOptimize_city`.`province_id` = `QSOptimize_province`.`id`) ;
django使用了INNER JOIN來得到省份的信息.
使用方法
select_related() 接受可變長參數,每一個參數是須要獲取的外鍵(父表的內容)的字段名,以及外鍵的外鍵的字段名、外鍵的外鍵的外鍵…。若要選擇外鍵的外鍵須要使用兩個下劃線「__」來鏈接。
例如得到張三的現居省份
>>> zhangs = Person.objects.select_related('living__province').get(firstname=u"張",lastname=u"三") >>> zhangs.living.province
觸發的SQL:
SELECT `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id`, `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id`, `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_person` INNER JOIN `QSOptimize_city` ON (`QSOptimize_person`.`living_id` = `QSOptimize_city`.`id`) INNER JOIN `QSOptimize_province` ON (`QSOptimize_city`.`province_id` = `QSOptimize_province`.`id`) WHERE (`QSOptimize_person`.`lastname` = '三' AND `QSOptimize_person`.`firstname` = '張' );
django使用了兩次INNER JOIN來完成請求,可是未指定的外鍵則不會被添加到結果中,例如張三的故鄉.
django1.7之前同時指定兩個外鍵使用
zhangs = Person.objects.select_related('hometown__province','living__province').get(firstname=u"張",lastname=u"三")
1.7後使用
zhangs = Person.objects.select_related('hometown__province').select_related('living__province').get(firstname=u"張",lastname=u"三")
depth參數
select_related() 接受depth參數,depth參數能夠肯定select_related的深度。Django會遞歸遍歷指定深度內的全部的OneToOneField和ForeignKey.
zhangs = Person.objects.select_related(depth = d)
d=1 至關於 select_related(‘hometown’,'living’)
d=2 至關於 select_related(‘hometown__province’,'living__province’)
select_related() 也能夠不加參數,這樣表示要求Django儘量深的select_related。例如:zhangs = Person.objects.select_related().get(firstname=u」張」,lastname=u」三」)。但要注意兩 點:
prefetch_related()
對於多對多字段(ManyToManyField)和一對多(ForeignKey)字段,可使用prefetch_related()來進行優化.
prefetch_related()和select_related()的設計目的很類似,都是爲了減小SQL查詢的數量,可是實現的方式不同。後者 是經過JOIN語句,在SQL查詢內解決問題。可是對於多對多關係,使用SQL語句解決就顯得有些不太明智,由於JOIN獲得的表將會很長,會致使SQL 語句運行時間的增長和內存佔用的增長。如有n個對象,每一個對象的多對多字段對應Mi條,就會生成Σ(n)Mi 行的結果表。
prefetch_related()的解決方法是,分別查詢每一個表,而後用Python處理他們之間的關係。
若是咱們要得到張三全部去過的城市.
>>> zhangs = Person.objects.prefetch_related('visitation').get(firstname=u"張",lastname=u"三") >>> for city in zhangs.visitation.all() : ... print city ...
觸發以下SQL語句
SELECT `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id` FROM `QSOptimize_person` WHERE (`QSOptimize_person`.`lastname` = '三' AND `QSOptimize_person`.`firstname` = '張'); SELECT (`QSOptimize_person_visitation`.`person_id`) AS `_prefetch_related_val`, `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id` FROM `QSOptimize_city` INNER JOIN `QSOptimize_person_visitation` ON (`QSOptimize_city`.`id` = `QSOptimize_person_visitation`.`city_id`) WHERE `QSOptimize_person_visitation`.`person_id` IN (1);
第一條SQL查詢僅僅是獲取張三的Person對象,第二條比較關鍵,它選取關係表`QSOptimize_person_visitation`中`person_id`爲張三的行,而後和`city`表內聯(INNER JOIN 也叫等值鏈接)獲得結果表.
或者咱們要得到湖北的全部城市名
>>> hb = Province.objects.prefetch_related('city_set').get(name__iexact=u"湖北省") >>> for city in hb.city_set.all(): ... city.name
SQL以下:
SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`name` LIKE '湖北省' ; SELECT `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id` FROM `QSOptimize_city` WHERE `QSOptimize_city`.`province_id` IN (1);
例如要得到全部姓張的人去過的省:
>>> zhangs = Person.objects.prefetch_related('visitation__province').filter(firstname__iexact=u'張') >>> for i in zhangs: ... for city in i.visitation.all(): ... print city.province
要注意的是,在使用QuerySet的時候,一旦在鏈式操做中改變了數據庫請求,以前用prefetch_related緩存的數據將會被忽略掉。這會導 致Django從新請求數據庫來得到相應的數據,從而形成性能問題。這裏提到的改變數據庫請求指各類filter()、exclude()等等最終會改變 SQL代碼的操做。而all()並不會改變最終的數據庫請求,所以是不會致使從新請求數據庫的。
plist = Person.objects.prefetch_related('visitation') [p.visitation.filter(name__icontains=u"市") for p in plist]
雖然已經查詢結果中包含全部所需的city的信息,但由於在循環體中對Person.visitation進行了filter操做,這顯然改變了數據庫請求。所以這些操做會忽略掉以前緩存到的數據,從新進行SQL查詢。
在Django小於1.7的版本
plist = Person.objects.prefetch_related('visitation') [[city for city in p.visitation.all() if u"市" in city.name] for p in plist]
在Django>1.7的版本
獲取全部人訪問過的城市中帶有「武」字和「州」的城市:
wus = City.objects.filter(name__icontains = u"武") zhous = City.objects.filter(name__icontains = u"州") plist = Person.objects.prefetch_related( Prefetch('visitation', queryset = wus, to_attr = "wu_city"), Prefetch('visitation', queryset = zhous, to_attr = "zhou_city"),) [p.wu_city for p in plist] [p.zhou_city for p in plist]
能夠經過傳入一個None來清空以前的prefetch_related。就像這樣:
prefetch_cleared_qset = qset.prefetch_related(None)
select_related()的效率要高於prefetch_related()。所以,最好在能用select_related()的地方儘可能使用它,也就是說,對於ForeignKey字段,避免使用prefetch_related()。
查詢家鄉是湖北的人
普通作法1
>>> hb = Province.objects.get(name__iexact=u"湖北省") >>> people = [] >>> for city in hb.city_set.all(): ... people.extend(city.birth.all())
pre作法
>>> hb = Province.objects.prefetch_related("city_set__birth").objects.get(name__iexact=u"湖北省") >>> people = [] >>> for city in hb.city_set.all(): ... people.extend(city.birth.all())
select作法
people = list(Person.objects.select_related("hometown__province").filter(hometown__province__name__iexact=u"湖北省"))
例子2:
一個訂單表:
class Order(models.Model): customer = models.ForeignKey(Person) orderinfo = models.CharField(max_length=50) time = models.DateTimeField(auto_now_add = True) def __unicode__(self): return self.orderinfo
若是咱們拿到了一個訂單的id 咱們要知道這個訂單的客戶去過的省份。由於有ManyToManyField顯然必需要用prefetch_related().
>>> plist = Order.objects.prefetch_related('customer__visitation__province').get(id=1) >>> for city in plist.customer.visitation.all(): ... print city.province.name
顯然,關係到了4個表:Order、Person、City、Province,根據prefetch_related()的特性就得有4次SQL查詢.
更好的辦法是先調用一次select_related()再調用prefetch_related(),最後再select_related()後面的表.
>>> plist = Order.objects.select_related('customer').prefetch_related('customer__visitation__province').get(id=1) >>> for city in plist.customer.visitation.all(): ... print city.province.name
值得注意的是,能夠在調用prefetch_related以前調用select_related,而且Django會按照你想的去作:先 select_related,而後利用緩存到的數據prefetch_related。然而一旦prefetch_related已經調 用,select_related將不起做用