首页 > 代码库 > select_related
select_related
作用:减少DB访问次数
from django.db import modelsclass Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): # __unicode__ on Python 2 return self.nameclass Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return self.nameclass 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 modelsclass City(models.Model): # ... passclass 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)
select_related
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。