一、Model类的元信息
1. Model类可以通过元信息类设置索引和排序信息
2. 元信息是在Model类中定义一个Meta子类
class Meta:
db_table = 'table_name'
index_together = ('tag1', 'tag2')
unique_together = ('tag3', 'tag4')
ordering = 'ordering_tag'
verbose_name = 'table_name'
二、基于对象查询的优化
1. 语法:only('tag_name1', ..., 'tag_name2') | defer('tag_name1', ..., 'tag_name2')
2. 属于QuerySet的方法
3. 用来优化面向对象查询的sql
4. only代表哪些字段参与查询,defer表示哪些字段不参与查询
三、自定义group_concat聚合函数
from django.db.models import Aggregate, CharField
class Concat(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)