select_related
作用:减少DB访问次数
from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): # __unicode__ on Python 2 return self.name class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return self.name class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): # __unicode__ on Python 2 return self.headline
e = Entry.objects.get(id=5) //访问一次数据库
b = e.blog //再访问一次数据库
e = Entry.objects.select_related('blog').get(id=5) //访问一次数据库
b = e.blog //不访问数据库
加入queryset中,顺序不重要
Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
Entry.objects.selected_related('blog').filter(pub_date__gt=timezone.now())
from django.db import models class City(models.Model): # ... pass class Person(models.Model): # ... hometown = models.ForeignKey(City) class Book(models.Model): # ... author = models.ForeignKey(Person)
b = Book.objects.select_related('author__hometown').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.
清空条件
without_relations = queryset.select_related(None)
多重查找
select_related('foo', 'bar')
控制查询缓存深度
b = Book.objects.select_related(depth=1).get(id=4)