5.18 Django select_related()

来源:互联网 发布:玩lol网络延迟怎么办 编辑:程序博客网 时间:2024/06/14 13:35

    select_related()是django QuerySet的API,它的作用是可以减少SQL query的次数。

    对于数据库访问,一般的想法是什么时候需要数据,什么时候访问数据库获取数据。更好的想法是提前知道自己需要的数据,然后有针对地一次性把数据都获取回来,这样就减少了数据库的访问次数,从而优化了网页性能。

    以django document中的例子为例:

# Hits the database.e = Entry.objects.get(id=5)# Hits the database again to get the related Blog object.b = e.blog

 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


文档里说是对于foreignkey会追溯到尽量远

class City(models.Model):    # ...    passclass Person(models.Model):    # ...    hometown = models.ForeignKey(City)class Book(models.Model):    # ...    author = models.ForeignKey(Person)b = Book.objects.select_related().get(id=4)p = b.author         # Doesn't hit the database.c = p.hometown       # Doesn't hit the database.b = Book.objects.get(id=4) # No select_related() in this example.p = b.author         # Hits the database.c = p.hometown       # Hits the database.

但是,通过我的实践检验,django1.5貌似不支持depth参数,默认就depth=1。(或者因为我不得不把foreignkey的null设为true)

所以在select_related()的时候,就要把需要的数据指定好,比如select_related('autor__hometown__somefieldElse')

例如:

def get_commits(**kwargs):     commits = Commit.objects.filter(**kwargs)     commits = commits.select_related('developer','project__name','project__code_host__commit_url')     return commits.only('commit_hash', 'submit_date',                         'summary',                         'lines_inserted', 'lines_deleted',                         'total_files', 'developer__full_name',                         'project__code_host__commit_url',                         'project__name')

project是commit的外键,code_host是project的外键,commit_url是code_host的字段。

如果在django1.5以上的版本中想要获取到commit_url的值,那么就得在select_related()中明确指定需要一起返回的字段。django1.5是反对depth参数的。

0 0
原创粉丝点击