查询优化

表数据

class UserInfo(AbstractUser):
    """
    用户信息
    """
    nid = models.BigAutoField(primary_key=True)
    nickname = models.CharField(verbose_name='昵称', max_length=32)
    telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
    avatar = models.FileField(verbose_name='头像',upload_to = 'avatar/',default="/avatar/default.png")
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
 
    fans = models.ManyToManyField(verbose_name='粉丝们',
                                  to='UserInfo',
                                  through='UserFans',
                                  related_name='f',
                                  through_fields=('user', 'follower'))
 
    def __str__(self):
        return self.username
 
class UserFans(models.Model):
    """
    互粉关系表
    """
    nid = models.AutoField(primary_key=True)
    user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
    follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')
 
class Blog(models.Model):
 
    """
    博客信息
    """
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='个人博客标题', max_length=64)
    site = models.CharField(verbose_name='个人博客后缀', max_length=32, unique=True)
    theme = models.CharField(verbose_name='博客主题', max_length=32)
    user = models.OneToOneField(to='UserInfo', to_field='nid')
    def __str__(self):
        return self.title
 
class Category(models.Model):
    """
    博主个人文章分类表
    """
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='分类标题', max_length=32)
 
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
 
class Article(models.Model):
 
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=50, verbose_name='文章标题')
    desc = models.CharField(max_length=255, verbose_name='文章描述')
    read_count = models.IntegerField(default=0)
    comment_count= models.IntegerField(default=0)
    up_count = models.IntegerField(default=0)
    down_count = models.IntegerField(default=0)
    category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)
    create_time = models.DateField(verbose_name='创建时间')
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
    tags = models.ManyToManyField(
        to="Tag",
        through='Article2Tag',
        through_fields=('article', 'tag'),
)
 
 
class ArticleDetail(models.Model):
    """
    文章详细表
    """
    nid = models.AutoField(primary_key=True)
    content = models.TextField(verbose_name='文章内容', )
 
    article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')
 
 
class Comment(models.Model):
    """
    评论表
    """
    nid = models.BigAutoField(primary_key=True)
    article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
    content = models.CharField(verbose_name='评论内容', max_length=255)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
 
    parent_comment = models.ForeignKey('self', blank=True, null=True, verbose_name='父级评论')
    user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
 
    up_count = models.IntegerField(default=0)
 
    def __str__(self):
        return self.content
 
class ArticleUpDown(models.Model):
    """
    点赞表
    """
    nid = models.AutoField(primary_key=True)
    user = models.ForeignKey('UserInfo', null=True)
    article = models.ForeignKey("Article", null=True)
    models.BooleanField(verbose_name='是否赞')
 
class CommentUp(models.Model):
    """
    点赞表
    """
    nid = models.AutoField(primary_key=True)
    user = models.ForeignKey('UserInfo', null=True)
    comment = models.ForeignKey("Comment", null=True)
 
 
class Tag(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='标签名称', max_length=32)
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
 
 
 
class Article2Tag(models.Model):
    nid = models.AutoField(primary_key=True)
    article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
    tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')

select_related

简单使用
对于一对一字段(OneToOneField)和外键字段(ForeignKey),可以使用select_related 来对QuerySet进行优化。

select_related 返回一个QuerySet,当执行它的查询时它沿着外键关系查询关联的对象的数据。它会生成一个复杂的查询并引起性能的损耗,但是在以后使用外键关系时将不需要数据库查询。

简单说,在对QuerySet使用select_related()函数后,Django会获取相应外键对应的对象,从而在之后需要的时候不必再查询数据库了。

下面的例子解释了普通查询和select_related() 查询的区别。

查询id=2的文章的分类名称,下面是一个标准的查询:

# Hits the database.
article=models.Article.objects.get(nid=2)
 
# Hits the database again to get the related Blog object.
print(article.category.title)
SELECT
    "blog_article"."nid",
    "blog_article"."title",
    "blog_article"."desc",
    "blog_article"."read_count",
    "blog_article"."comment_count",
    "blog_article"."up_count",
    "blog_article"."down_count",
    "blog_article"."category_id",
    "blog_article"."create_time",
     "blog_article"."blog_id",
     "blog_article"."article_type_id"
             FROM "blog_article"
             WHERE "blog_article"."nid" = 2; args=(2,)
 
SELECT
     "blog_category"."nid",
     "blog_category"."title",
     "blog_category"."blog_id"
              FROM "blog_category"
              WHERE "blog_category"."nid" = 4; args=(4,)

如果我们使用select_related()函数:

articleList=models.Article.objects.select_related("category").all()
 
 
    for article_obj in articleList:
        #  Doesn't hit the database, because article_obj.category
        #  has been prepopulated in the previous query.
        print(article_obj.category.title)
SELECT
     "blog_article"."nid",
     "blog_article"."title",
     "blog_article"."desc",
     "blog_article"."read_count",
     "blog_article"."comment_count",
     "blog_article"."up_count",
     "blog_article"."down_count",
     "blog_article"."category_id",
     "blog_article"."create_time",
     "blog_article"."blog_id",
     "blog_article"."article_type_id",
 
     "blog_category"."nid",
     "blog_category"."title",
     "blog_category"."blog_id"
 
FROM "blog_article"
LEFT OUTER JOIN "blog_category" ON ("blog_article"."category_id" = "blog_category"."nid");

多外键查询

这是针对category的外键查询,如果是另外一个外键呢?让我们一起看下:

article=models.Article.objects.select_related("category").get(nid=1)
print(article.articledetail)

观察logging结果,发现依然需要查询两次,所以需要改为:

article=models.Article.objects.select_related("category","articledetail").get(nid=1)
print(article.articledetail)

或者:

article=models.Article.objects
             .select_related("category")
             .select_related("articledetail")
             .get(nid=1)  # django 1.7 支持链式操作
print(article.articledetail)
SELECT
 
    "blog_article"."nid",
    "blog_article"."title",
    ......
 
    "blog_category"."nid",
    "blog_category"."title",
    "blog_category"."blog_id",
 
    "blog_articledetail"."nid",
    "blog_articledetail"."content",
    "blog_articledetail"."article_id"
 
   FROM "blog_article"
   LEFT OUTER JOIN "blog_category" ON ("blog_article"."category_id" = "blog_category"."nid")
   LEFT OUTER JOIN "blog_articledetail" ON ("blog_article"."nid" = "blog_articledetail"."article_id")
   WHERE "blog_article"."nid" = 1; args=(1,)

深层查询

# 查询id=1的文章的用户姓名
 
    article=models.Article.objects.select_related("blog").get(nid=1)
    print(article.blog.user.username)

依然需要查询两次:

SELECT
    "blog_article"."nid",
    "blog_article"."title",
    ......
 
     "blog_blog"."nid",
     "blog_blog"."title",
 
   FROM "blog_article" INNER JOIN "blog_blog" ON ("blog_article"."blog_id" = "blog_blog"."nid")
   WHERE "blog_article"."nid" = 1;
 
 
 
 
SELECT
    "blog_userinfo"."password",
    "blog_userinfo"."last_login",
    ......
 
FROM "blog_userinfo"
WHERE "blog_userinfo"."nid" = 1;

这是因为第一次查询没有query到userInfo表,所以,修改如下:

article=models.Article.objects.select_related("blog__user").get(nid=1)
print(article.blog.user.username)
SELECT
 
"blog_article"."nid", "blog_article"."title",
......
 
 "blog_blog"."nid", "blog_blog"."title",
......
 
 "blog_userinfo"."password", "blog_userinfo"."last_login",
......
 
FROM "blog_article"
 
INNER JOIN "blog_blog" ON ("blog_article"."blog_id" = "blog_blog"."nid")
 
INNER JOIN "blog_userinfo" ON ("blog_blog"."user_id" = "blog_userinfo"."nid")
WHERE "blog_article"."nid" = 1;

总结

  1. select_related主要针一对一和多对一关系进行优化。
  2. select_related使用SQL的JOIN语句进行优化,通过减少SQL查询的次数来进行优化、提高性能。
    3.可以通过可变长参数指定需要select_related的字段名。也可以通过使用双下划线“__”连接字段名来实现指定的递归查询。
  3. 没有指定的字段不会缓存,没有指定的深度不会缓存,如果要访问的话Django会再次进行SQL查询。
    也可以通过depth参数指定递归的深度,Django会自动缓存指定深度内所有的字段。如果要访问指定深度外的字段,Django会再次进行SQL查询。
  4. 也接受无参数的调用,Django会尽可能深的递归查询所有的字段。但注意有Django递归的限制和性能的浪费。
  5. Django >= 1.7,链式调用的select_related相当于使用可变长参数。Django < 1.7,链式调用会导致前边的select_related失效,只保留最后一个。

prefetch_related()

对于多对多字段(ManyToManyField)和一对多字段,可以使用prefetch_related()来进行优化。

prefetch_related()和select_related()的设计目的很相似,都是为了减少SQL查询的数量,但是实现的方式不一样。后者是通过JOIN语句,在SQL查询内解决问题。但是对于多对多关系,使用SQL语句解决就显得有些不太明智,因为JOIN得到的表将会很长,会导致SQL语句运行时间的增加和内存占用的增加。若有n个对象,每个对象的多对多字段对应Mi条,就会生成Σ(n)Mi 行的结果表。

prefetch_related()的解决方法是,分别查询每个表,然后用Python处理他们之间的关系。

# 查询所有文章关联的所有标签
    article_obj=models.Article.objects.all()
    for i in article_obj:
 
        print(i.tags.all())  #4篇文章: hits database 5

改为prefetch_related:

# 查询所有文章关联的所有标签
    article_obj=models.Article.objects.prefetch_related("tags").all()
    for i in article_obj:
 
        print(i.tags.all())  #4篇文章: hits database 2
SELECT "blog_article"."nid",
               "blog_article"."title",
               ......
 
FROM "blog_article";
 
 
 
SELECT
  ("blog_article2tag"."article_id") AS "_prefetch_related_val_article_id",
  "blog_tag"."nid",
  "blog_tag"."title",
  "blog_tag"."blog_id"
   FROM "blog_tag"
  INNER JOIN "blog_article2tag" ON ("blog_tag"."nid" = "blog_article2tag"."tag_id")
  WHERE "blog_article2tag"."article_id" IN (1, 2, 3, 4);

你可能感兴趣的:(查询优化)