1. Aggregation query
Aggregation query refers to a partial or complete statistical query on the data of a field in a data table. The average price of all books in the difference Book data table, the total number of all books, etc. need to use aggregation queries.
Aggregation queries are divided into:
(1) Entire table aggregation
Import of aggregate functions:
from django.db.models import *
Aggregate functions: Sum, Avg, Count, Max, Min
Syntax:
MyModel.objects.aggregate(result variable name=aggregate function('column name'))
The result variable name is the Count(*) as alias in the sql statement. That is to say, the alias is the parameter of the result variable name in our parameter. By expressing in the form of a dictionary, it is convenient to perform data retrieval and data acquisition in the program.
(2) Group aggregation
Syntax:
QuerySet.annotate (result variable name = aggregation function ('column name'))
return value:
QuerySet
###2. Native database operation
Scheme 1:
Query:
directly use MyModel.objects.raw() to query the database.
Syntax:
MyModel.objects.raw(sql statement, splicing parameters)
Return value:
RawQuerySet collection object [only supports basic operations, such as loop]
Example:
It can be found that the item here is an object.
Django officially does not recommend using sql statements for queries. Because there may be sql injection vulnerabilities that cause serious defects and problems in web applications.
Therefore, in the splicing parameters of the sql statement, sql injection attacks can be prevented through parameterization.
Example:
When we do not use parameterization for parameter passing, all book information is exported.
When we enabled parameterized queries, we successfully prevented sql injection attacks.