在數據庫有外鍵的時候,使用 select_related() 和 prefetch_related() 能夠很好的減小數據庫請求的次數,從而提升性能。本文經過一個簡單的例子詳解這兩個函數的做用。雖然QuerySet的文檔中已經詳細說明了,但本文試圖從QuerySet觸發的SQL語句來分析工做方式,從而進一步瞭解Django具體的運做方式。
假定一個我的信息系統,須要記錄系統中各我的的故鄉、居住地、以及到過的城市。數據庫設計以下:python
Models.py 內容以下:mysql
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
注1:建立的app名爲「QSOptimize」sql
注2:爲了簡化起見,qsoptimize_province
表中只有2條數據:湖北省和廣東省,qsoptimize_city
表中只有三條數據:武漢市、十堰市和廣州市數據庫
對於一對一字段(OneToOneField)和外鍵字段(ForeignKey),可使用select_related 來對QuerySet進行優化django
在對QuerySet使用select_related()函數後,Django會獲取相應外鍵對應的對象,從而在以後須要的時候沒必要再查詢數據庫了。以上例說明,若是咱們須要打印數據庫中的全部市及其所屬省份,最直接的作法是:緩存
>>> citys = City.objects.all() >>> for c in citys: ... print c.province ...
這樣會致使線性的SQL查詢,若是對象數量n太多,每一個對象中有k個外鍵字段的話,就會致使n*k+1次SQL查詢。在本例中,由於有3個city對象就致使了4次SQL查詢:app
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 ;
注:這裏的SQL語句是直接從Django的logger:‘django.db.backends’輸出出來的數據庫設計
若是咱們使用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來得到省份的信息。順便一提這條SQL查詢獲得的結果以下:
+----+-----------+-------------+----+-----------+ | id | name | province_id | id | name | +----+-----------+-------------+----+-----------+ | 1 | 武漢市 | 1 | 1 | 湖北省 | | 2 | 廣州市 | 2 | 2 | 廣東省 | | 3 | 十堰市 | 1 | 1 | 湖北省 | +----+-----------+-------------+----+-----------+ 3 rows in set (0.00 sec)
函數支持以下三種用法:
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使用了2次 INNER JOIN 來完成請求,得到了city表和province表的內容並添加到結果表的相應列,這樣在調用 zhangs.living的時候也沒必要再次進行SQL查詢。
+----+-----------+----------+-------------+-----------+----+-----------+-------------+----+-----------+ | id | firstname | lastname | hometown_id | living_id | id | name | province_id | id | name | +----+-----------+----------+-------------+-----------+----+-----------+-------------+----+-----------+ | 1 | 張 | 三 | 3 | 1 | 1 | 武漢市 | 1 | 1 | 湖北省 | +----+-----------+----------+-------------+-----------+----+-----------+-------------+----+-----------+ 1 row in set (0.00 sec)
然而,未指定的外鍵則不會被添加到結果中。這時候若是須要獲取張三的故鄉就會進行SQL查詢了:
>>> zhangs.hometown.province
SELECT `QSOptimize_city`.`id`, `QSOptimize_city`.`name`, `QSOptimize_city`.`province_id` FROM `QSOptimize_city` WHERE `QSOptimize_city`.`id` = 3 ; SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` = 1
同時,若是不指定外鍵,就會進行兩次查詢。若是深度更深,查詢的次數更多。
值得一提的是,從Django 1.7開始,select_related()函數的做用方式改變了。在本例中,若是要同時得到張三的故鄉和現居地的省份,在1.7之前你只能這樣作:
>>> zhangs = Person.objects.select_related('hometown__province','living__province').get(firstname=u"張",lastname=u"三") >>> zhangs.hometown.province >>> zhangs.living.province
可是1.7及以上版本,你能夠像和queryset的其餘函數同樣進行鏈式操做:
>>> zhangs = Person.objects.select_related('hometown__province').select_related('living__province').get(firstname=u"張",lastname=u"三") >>> zhangs.hometown.province >>> zhangs.living.province
若是你在1.7如下版本這樣作了,你只會得到最後一個操做的結果,在本例中就是隻有現居地而沒有故鄉。在你打印故鄉省份的時候就會形成兩次SQL查詢。
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」三」)。但要注意兩點:
對於多對多字段(ManyToManyField)和一對多字段,可使用prefetch_related()來進行優化。或許你會說,沒有一個叫OneToManyField的東西啊。實際上 ,ForeignKey就是一個多對一的字段,而被ForeignKey關聯的字段就是一對多字段了。
prefetch_related()和select_related()的設計目的很類似,都是爲了減小SQL查詢的數量,可是實現的方式不同。後者是經過JOIN語句,在SQL查詢內解決問題。可是對於多對多關係,使用SQL語句解決就顯得有些不太明智,由於JOIN獲得的表將會很長,會致使SQL語句運行時間的增長和內存佔用的增長。如有n個對象,每一個對象的多對多字段對應Mi條,就會生成Σ(n)Mi 行的結果表。prefetch_related()的解決方法是,分別查詢每一個表,而後用Python處理他們之間的關係。繼續以上邊的例子進行說明,若是咱們要得到張三全部去過的城市,使用prefetch_related()應該是這麼作:
>>> 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 也叫等值鏈接)獲得結果表。
+----+-----------+----------+-------------+-----------+ | id | firstname | lastname | hometown_id | living_id | +----+-----------+----------+-------------+-----------+ | 1 | 張 | 三 | 3 | 1 | +----+-----------+----------+-------------+-----------+ 1 row in set (0.00 sec) +-----------------------+----+-----------+-------------+ | _prefetch_related_val | id | name | province_id | +-----------------------+----+-----------+-------------+ | 1 | 1 | 武漢市 | 1 | | 1 | 2 | 廣州市 | 2 | | 1 | 3 | 十堰市 | 1 | +-----------------------+----+-----------+-------------+ 3 rows in set (0.00 sec)
顯然張三武漢、廣州、十堰都去過。
又或者,咱們要得到湖北的全部城市名,能夠這樣:
>>> 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);
獲得的表:
+----+-----------+ | id | name | +----+-----------+ | 1 | 湖北省 | +----+-----------+ 1 row in set (0.00 sec) +----+-----------+-------------+ | id | name | province_id | +----+-----------+-------------+ | 1 | 武漢市 | 1 | | 3 | 十堰市 | 1 | +----+-----------+-------------+ 2 rows in set (0.00 sec)
咱們能夠看見,prefetch使用的是 IN 語句實現的。這樣,在QuerySet中的對象數量過多的時候,根據數據庫特性的不一樣有可能形成性能問題。
prefetch_related()在Django < 1.7 只有這一種用法。和select_related()同樣,prefetch_related()也支持深度查詢,例如要得到全部姓張的人去過的省:
>>> zhangs = Person.objects.prefetch_related('visitation__province').filter(firstname__iexact=u'張') >>> for i in zhangs: ... for city in i.visitation.all(): ... print city.province ...
觸發的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`.`firstname` LIKE '張' ; 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, 4); SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` IN (1, 2);
得到的結果:
+----+-----------+----------+-------------+-----------+ | id | firstname | lastname | hometown_id | living_id | +----+-----------+----------+-------------+-----------+ | 1 | 張 | 三 | 3 | 1 | | 4 | 張 | 六 | 2 | 2 | +----+-----------+----------+-------------+-----------+ 2 rows in set (0.00 sec) +-----------------------+----+-----------+-------------+ | _prefetch_related_val | id | name | province_id | +-----------------------+----+-----------+-------------+ | 1 | 1 | 武漢市 | 1 | | 1 | 2 | 廣州市 | 2 | | 4 | 2 | 廣州市 | 2 | | 1 | 3 | 十堰市 | 1 | +-----------------------+----+-----------+-------------+ 4 rows in set (0.00 sec) +----+-----------+ | id | name | +----+-----------+ | 1 | 湖北省 | | 2 | 廣東省 | +----+-----------+ 2 rows in set (0.00 sec)
值得一提的是,鏈式prefetch_related會將這些查詢添加起來,就像1.7中的select_related那樣。
要注意的是,在使用QuerySet的時候,一旦在鏈式操做中改變了數據庫請求,以前用prefetch_related緩存的數據將會被忽略掉。這會致使Django從新請求數據庫來得到相應的數據,從而形成性能問題。這裏提到的改變數據庫請求指各類filter()、exclude()等等最終會改變SQL代碼的操做。而all()並不會改變最終的數據庫請求,所以是不會致使從新請求數據庫的。
舉個例子,要獲取全部人訪問過的城市中帶有「市」字的城市,這樣作會致使大量的SQL查詢:
plist = Person.objects.prefetch_related('visitation') [p.visitation.filter(name__icontains=u"市") for p in plist]
由於數據庫中有4人,致使了2+4次SQL查詢:
SELECT `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id` FROM `QSOptimize_person`; 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, 2, 3, 4); SELECT `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` = 1 AND `QSOptimize_city`.`name` LIKE '%市%' ); SELECT `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` = 2 AND `QSOptimize_city`.`name` LIKE '%市%' ); SELECT `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` = 3 AND `QSOptimize_city`.`name` LIKE '%市%' ); SELECT `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` = 4 AND `QSOptimize_city`.`name` LIKE '%市%' );
詳細分析一下這些請求事件。
衆所周知,QuerySet是lazy的,要用的時候纔會去訪問數據庫。運行到第二行Python代碼時,for循環將plist看作iterator,這會觸發數據庫查詢。最初的兩次SQL查詢就是prefetch_related致使的。
雖然已經查詢結果中包含全部所需的city的信息,但由於在循環體中對Person.visitation進行了filter操做,這顯然改變了數據庫請求。所以這些操做會忽略掉以前緩存到的數據,從新進行SQL查詢。
可是若是有這樣的需求了應該怎麼辦呢?在Django >= 1.7,能夠經過下一節的Prefetch對象來實現,若是你的環境是Django < 1.7,能夠在Python中完成這部分操做。
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,能夠用Prefetch對象來控制prefetch_related函數的行爲。
注:因爲我沒有安裝1.7版本的Django環境,本節內容是參考Django文檔寫的,沒有進行實際的測試。
Prefetch對象的特徵:
繼續上面的例子,獲取全部人訪問過的城市中帶有「武」字和「州」的城市:
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]
注:這段代碼沒有在實際環境中測試過,如有不正確的地方請指正。
順帶一提,Prefetch對象和字符串參數能夠混用。
能夠經過傳入一個None來清空以前的prefetch_related。就像這樣:
>>> prefetch_cleared_qset = qset.prefetch_related(None)
若是咱們想要得到全部家鄉是湖北的人,最無腦的作法是先得到湖北省,再得到湖北的全部城市,最後得到故鄉是這個城市的人。就像這樣:
>>> hb = Province.objects.get(name__iexact=u"湖北省") >>> people = [] >>> for city in hb.city_set.all(): ... people.extend(city.birth.all()) ...
顯然這不是一個明智的選擇,由於這樣作會致使1+(湖北省城市數)次SQL查詢。反正是個反例,致使的查詢和得到掉結果就不列出來了。
prefetch_related() 或許是一個好的解決方法,讓咱們來看看。
>>> 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()) ...
由於是一個深度爲2的prefetch,因此會致使3次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); SELECT `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id` FROM `QSOptimize_person` WHERE `QSOptimize_person`.`hometown_id` IN (1, 3);
嗯…看上去不錯,可是3次查詢麼?倒過來查詢可能會更簡單?
>>> people = list(Person.objects.select_related("hometown__province").filter(hometown__province__name__iexact=u"湖北省"))
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`.`hometown_id` = `QSOptimize_city`.`id`) INNER JOIN `QSOptimize_province` ON (`QSOptimize_city`.`province_id` = `QSOptimize_province`.`id`) WHERE `QSOptimize_province`.`name` LIKE '湖北省';
+----+-----------+----------+-------------+-----------+----+--------+-------------+----+--------+ | id | firstname | lastname | hometown_id | living_id | id | name | province_id | id | name | +----+-----------+----------+-------------+-----------+----+--------+-------------+----+--------+ | 1 | 張 | 三 | 3 | 1 | 3 | 十堰市 | 1 | 1 | 湖北省 | | 2 | 李 | 四 | 1 | 3 | 1 | 武漢市 | 1 | 1 | 湖北省 | | 3 | 王 | 麻子 | 3 | 2 | 3 | 十堰市 | 1 | 1 | 湖北省 | +----+-----------+----------+-------------+-----------+----+--------+-------------+----+--------+ 3 rows in set (0.00 sec)
徹底沒問題。不只SQL查詢的數量減小了,python程序上也精簡了。
select_related()的效率要高於prefetch_related()。所以,最好在能用select_related()的地方儘可能使用它,也就是說,對於ForeignKey字段,避免使用prefetch_related()。
對於同一個QuerySet,你能夠同時使用這兩個函數。
在咱們一直使用的例子上加一個model:Order (訂單)
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()。若是隻用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 `QSOptimize_order`.`id`, `QSOptimize_order`.`customer_id`, `QSOptimize_order`.`orderinfo`, `QSOptimize_order`.`time` FROM `QSOptimize_order` WHERE `QSOptimize_order`.`id` = 1 ; SELECT `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id` FROM `QSOptimize_person` WHERE `QSOptimize_person`.`id` IN (1); 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); SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` IN (1, 2);
+----+-------------+---------------+---------------------+ | id | customer_id | orderinfo | time | +----+-------------+---------------+---------------------+ | 1 | 1 | Info of Order | 2014-08-10 17:05:48 | +----+-------------+---------------+---------------------+ 1 row in set (0.00 sec) +----+-----------+----------+-------------+-----------+ | id | firstname | lastname | hometown_id | living_id | +----+-----------+----------+-------------+-----------+ | 1 | 張 | 三 | 3 | 1 | +----+-----------+----------+-------------+-----------+ 1 row in set (0.00 sec) +-----------------------+----+--------+-------------+ | _prefetch_related_val | id | name | province_id | +-----------------------+----+--------+-------------+ | 1 | 1 | 武漢市 | 1 | | 1 | 2 | 廣州市 | 2 | | 1 | 3 | 十堰市 | 1 | +-----------------------+----+--------+-------------+ 3 rows in set (0.00 sec) +----+--------+ | id | name | +----+--------+ | 1 | 湖北省 | | 2 | 廣東省 | +----+--------+ 2 rows in set (0.00 sec)
更好的辦法是先調用一次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 ...
這樣只會有3次SQL查詢,Django會先作select_related,以後prefetch_related的時候會利用以前緩存的數據,從而避免了1次額外的SQL查詢:
SELECT `QSOptimize_order`.`id`, `QSOptimize_order`.`customer_id`, `QSOptimize_order`.`orderinfo`, `QSOptimize_order`.`time`, `QSOptimize_person`.`id`, `QSOptimize_person`.`firstname`, `QSOptimize_person`.`lastname`, `QSOptimize_person`.`hometown_id`, `QSOptimize_person`.`living_id` FROM `QSOptimize_order` INNER JOIN `QSOptimize_person` ON (`QSOptimize_order`.`customer_id` = `QSOptimize_person`.`id`) WHERE `QSOptimize_order`.`id` = 1 ; 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); SELECT `QSOptimize_province`.`id`, `QSOptimize_province`.`name` FROM `QSOptimize_province` WHERE `QSOptimize_province`.`id` IN (1, 2);
+----+-------------+---------------+---------------------+----+-----------+----------+-------------+-----------+ | id | customer_id | orderinfo | time | id | firstname | lastname | hometown_id | living_id | +----+-------------+---------------+---------------------+----+-----------+----------+-------------+-----------+ | 1 | 1 | Info of Order | 2014-08-10 17:05:48 | 1 | 張 | 三 | 3 | 1 | +----+-------------+---------------+---------------------+----+-----------+----------+-------------+-----------+ 1 row in set (0.00 sec) +-----------------------+----+--------+-------------+ | _prefetch_related_val | id | name | province_id | +-----------------------+----+--------+-------------+ | 1 | 1 | 武漢市 | 1 | | 1 | 2 | 廣州市 | 2 | | 1 | 3 | 十堰市 | 1 | +-----------------------+----+--------+-------------+ 3 rows in set (0.00 sec) +----+--------+ | id | name | +----+--------+ | 1 | 湖北省 | | 2 | 廣東省 | +----+--------+ 2 rows in set (0.00 sec)
轉自