Django model layer optimization
First, my ultimate goal is to develop PythonDjango + campus micro-channel application applets, so I see this series you can view some useful elements, but some elements are the notes I need to record the record, not a collection of the entire project.
Django model layer change and migration:
-
makemigration appname
-
migrate to execute database
-
selmigrate appname 0014 to see the implementation of sql statement (20)
-
showmigration appname change history display applications and migration history
Django Model layer - lazy loading, preloaded
-
The root of the problem lazy loading
-
Pre-loaded method
-
Comparative Performance Data
Django layer optimization model (long link)
-
Processing logic database connection
-
Avoid negative optimization
-
Position storage database connection: thread-local variables
-
The maximum number of connections supported by the database
- Open a command line navicat
- show variables like “%max_connection%”;
- set global max_connections = 200 to 200
-
CONN_MAX_AGE (maximum number of connections) Configuration Guide
- Number of deployment threads: n <database maximum number of connections
- Development model is not recommended for use CONN_MAX_AGE
- Each request will create a thread
-
-
Theoretical results
Django database model layer Practices
-
The proper use of the index
- Index should be indexed column
- Not the index should not be indexed column
-
Use iterator iterator iteration QuerySet
- When QuerySet very large, iterators save memory
-
Understand property cache object
- Can not invoke the property: it is the default data does not contain the foreign key
- Callable properties: it is a foreign key, data, and many to many, may be a function call,
- The callable Python attributes assigned to a variable, when called again, you do not need to call the database, but you can call the data Python variable (to improve performance)
-
Work on the database to make the database
- Filter: exclude, filter attributes
- Polymerization: polymerization using function annotate
- When necessary, use native SQL
-
The right to retrieve data
- Field being indexed retrieval using
- Using the unique modified Field Search
-
Do not make unnecessary retrieval
- Use QuerySet Values (), Value_list () function returns a structure of the container Python
- The length of the query results using QuerySet.count () instead of len (QuerySet)
- Whether a judge is empty yo QuerySet.exists () instead if QuerySet
-
Do not make unnecessary sorting
- Do not make unnecessary sorting
-
Batch operations
- Large amounts of data, bulk operations