Django (meta-information) metaclass indexed
ORM Query (sql optimization) optimization
Custom aggregate functions
Django metaclass indexed ---- index: a main purpose of the index is to speed up the data retrieval table, the index is the result of an algorithm optimized, so look for the number to be much less. Thus, the index is used to locate.
class Book(models.Model) name = models.CharField(max_length=64) class Meta: # Custom Table Name db_table = 'table_name' # Joint index: a main purpose of the index is to speed up data retrieval table index_together = ('tag1', 'tag2') # Joint unique index: two fields considered all repeat repeat unique_together = ('tag3', 'tag4') # Sort field ordering = 'ordering_tag' # / Admin table name displayed / in verbose_name = 'table_name'
ORM Query (sql optimization) optimized ---- little bit about it
(1) only () to check only certain fields, you want to view other fields, follow-up can point out other fields uql1 = Book.objects.all (). only ( "name", "price") # only checked the "name", "price" of two fields All fields Book.objects.all () # books are checked again print (uq11.first (). gender) # follow-up can point out the other fields, but himself re-execute the query field sql, equivalent to re-checked again (2) defer () except for certain fields, others are checked Book.objects.all (). Defer ( "name", "price") # In addition to "name", "price" of two fields, other fields are checked (3) values # can not point out the subsequent fields of the other Book.objects.values ( "name", "price") # only checked the "name", "price" of two fields
Custom aggregate functions - can to practice
from django.db.models import Aggregate, CharField # Custom name aggregate function class Concat (Aggregate): # write a class that inherits 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") )