码迷,mamicode.com
首页 > 其他好文 > 详细

select_related

时间:2015-01-07 23:33:39      阅读:166      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!