在线亚洲AV日韩AV综合AV,国产订精品电影,久久国产精品蜜

      <thead id="u9ncv"><del id="u9ncv"><rp id="u9ncv"></rp></del></thead>

        <thead id="u9ncv"></thead>

        <thead id="u9ncv"><s id="u9ncv"></s></thead>

          <strike id="u9ncv"></strike>
          <table id="u9ncv"><form id="u9ncv"></form></table>
        1. <strike id="u9ncv"></strike>
        2. 使用幫助 | 聯系電話:400-880-0256 0769-23037585 21686281

          實例詳解Django的 select_related 和 prefetch_related 函數對 QuerySet 查

          作者:admin 發表于:2014-08-18 點擊:831  保護視力色:

          這是本系列的最后一篇,主要是select_related() 和 prefetch_related() 的最佳實踐。

          第一篇在這里?講例子和select_related()

          第二篇在這里?講prefetch_related()

           

          4. 一些實例

          選擇哪個函數

          如果我們想要獲得所有家鄉是湖北的人,最無腦的做法是先獲得湖北省,再獲得湖北的所有城市,最后獲得故鄉是這個城市的人。就像這樣:
          >>> 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)

          值得注意的是,可以在調用prefetch_related之前調用select_related,并且Django會按照你想的去做:先select_related,然后利用緩存到的數據prefetch_related。然而一旦prefetch_related已經調用,select_related將不起作用。

           

          小結

          1. 因為select_related()總是在單次SQL查詢中解決問題,而prefetch_related()會對每個相關表進行SQL查詢,因此select_related()的效率通常比后者高。
          2. 鑒于第一條,盡可能的用select_related()解決問題。只有在select_related()不能解決問題的時候再去想prefetch_related()。
          3. 你可以在一個QuerySet中同時使用select_related()和prefetch_related(),從而減少SQL查詢的次數。
          4. 只有prefetch_related()之前的select_related()是有效的,之后的將會被無視掉。
          關于這兩個函數,我能想到的東西目前只有這么多。不過基于一些個人原因,寫第三篇時間比較短,寫的有些倉促。如果什么時候又想起了什么,我會在這篇博文中添加。

          實例詳解Django的 select_related 和 prefetch_related 函數對 QuerySet 查詢的優化(三),首發于博客 - 伯樂在線。

          在线亚洲AV日韩AV综合AV,国产订精品电影,久久国产精品蜜