django select_related() 联表查询

select_related()官方解释

Returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of foreign-key relationships won't require database queries.

The following examples illustrate the difference between plain lookups and select_related() lookups. Here's standard lookup:

# Hits the database.
e = Entry.objects.get(id=5)

# Hits the database again to get the related Blog object.
b = e.blog

And here's select_related lookup:

# Hits the database.
e = Entry.objects.select_related().get(id=5)

# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog

简而言之..
他们由这种

(0.000) SELECT `default_docs`.`id`, `default_docs`.`title`, `default_docs`.`document`, `default_docs`.`user_id` FROM `default_docs` INNER JOIN `default_user` ON (`default_docs`.`user_id` = `default_user`.`id`) WHERE `default_user`.`username` = 'wc' ; args=('wc',)
(0.000) SELECT `default_user`.`id`, `default_user`.`username`, `default_user`.`password` FROM `default_user` WHERE `default_user`.`id` = 1 ; args=(1,)

转成这种

(0.000) SELECT `default_docs`.`id`, `default_docs`.`title`, `default_docs`.`document`, `default_docs`.`user_id`, `default_user`.`id`, `default_user`.`username`, `default_user`.`password` FROM `default_docs` INNER JOIN `default_user` ON (`default_docs`.`user_id` = `default_user`.`id`) WHERE `default_user`.`username` = 'wc' ; args=('wc',)

也就是他一次联表查询(inner join)了,且设置了Field

posted @ 2012-04-09 15:03  无嗔  阅读(2643)  评论(0编辑  收藏  举报