• 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)

  • 相关阅读:
    LINUX系统运行查看
    MySQL数据库中tinyint类型字段读取数据为true和false (MySQL的boolean和tinyint(1))
    mysql DATE_FORMAT 年月日时分秒格式化
    fastJson泛型如何转换
    查找java程序进程快速指令jps
    vim快捷键
    mysql全库搜索指定字符串
    mysql一次性删除所有表而不删除数据库
    一键安装Docker图形化管理界面-Shipyard
    hadoop性能测试
  • 原文地址:https://www.cnblogs.com/tuifeideyouran/p/4209571.html
Copyright © 2020-2023  润新知