首页 > 其他 > 详细

select_related

时间:2015-01-07 23:30:34      阅读:437      评论:0      收藏:0      [点我收藏+]

作用:减少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         # Doesnt hit the database.
c = p.hometown       # Doesnt 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

原文:http://www.cnblogs.com/tuifeideyouran/p/4209571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!