django中的聚合索引

Django(元信息)元类建索引

ORM查询(sql优化)优化

自定义聚合函数

Django的元类建索引————索引:索引的一个主要目的就是加快检索表中数据,索引是经过某种算法优化过的,因而查找次数要少的多。因此,索引是用来定位的。

class Book(models.Model)
    name = models.CharField(max_length=64)

    class Meta:
        # 自定义表名
        db_table = 'table_name'
        # 联合索引: 索引的一个主要目的就是加快检索表中数据
        index_together = ('tag1', 'tag2')
        # 联合唯一索引:两个字段全部重复才算重复
        unique_together = ('tag3', 'tag4')
        # 排序字段
        ordering = 'ordering_tag'
        # /admin/中显示的表名称
        verbose_name = 'table_name'

  

  

ORM查询(sql优化)优化————稍微了解一下就可以了

(1)only() 只查某些字段,要查看其他的字段,后续也能点出其他字段
    uql1 = Book.objects.all().only("name","price")   # 只查了 "name","price" 两个字段
    Book.objects.all()    # 书的所有字段都查了一遍
    print(uq11.first().gender)    # 后续也能点出其他字段,不过自己又重新执行了查询该字段的sql,相当于在重新查了一遍

(2)defer()  除了某些字段,其他的都查
    Book.objects.all().defer("name","price")  # 除了 "name","price" 两个字段,其他的字段都查

(3)values  # 后续不能再点出其他字段了
    Book.objects.values("name","price")   # 只查了 "name","price" 两个字段

  自定义聚合函数——可以去实践

from django.db.models import Aggregate, CharField

    # 自定义聚合函数的名字
    class Concat(Aggregate):  # 写一个类继承Aggregate,
        function = 'GROUP_CONCAT'
        template = '%(function)s(%(distinct)s%(expressions)s)'

        def __init__(self, expression, distinct=False, **extra):
            super(Concat, self).__init__(
                expression,
                distinct='DISTINCT ' if distinct else '',
                output_field=CharField(),
                **extra)

    eg: Book.objects.aggregate( name=Concat("name") )

  

  

原文地址:https://www.cnblogs.com/manjian/p/11796355.html