Django ORM – Multi-Table Examples (Aggregation and Grouping Queries)
Aggregation queries (aggregate)
Aggregation query functions perform a calculation on a set of values and return a single value.
Before using aggregation queries in Django, you must first import Avg, Max, Min, Count, Sum (capitalized) from django.db.models.
from django.db.models import Avg,Max,Min,Count,Sum # 引入函数
The data type of the return value of an aggregation query is a dictionary.
The aggregate function aggregate() is a terminating clause of QuerySet that produces a summary value, equivalent to count().
After using aggregate(), the data type becomes a dictionary, and you can no longer use some APIs of the QuerySet data type.
The date data type (DateField) can use Max and Min.
In the returned dictionary: the default key name is (attribute name plus __aggregate function name), and the value is the computed aggregate value.
To customize the key names of the returned dictionary, you can use aliases:
aggregate(别名 = 聚合函数名("属性名称"))
Calculate the average price of all books:
Example
from
django.
db
.
models
import
Avg
,
Max
,
Min
,
Count
,
Sum
Import functions
...
res
=
models.
Book
.
objects
.
aggregate
(
Avg
(
"price"
)
)
(
res
,
type
(
res
)
)
...

Calculate the quantity, the highest price, and the lowest price of all books:
Example
res
=
models.
Book
.
objects
.
aggregate
(
c
=
Count
(
"id"
)
,
max
=
Max
(
"price"
)
,
min
=
Min
(
"price"
)
)
(
res
,
type
(
res
)

Grouping queries (annotate)
Grouping queries generally use aggregate functions, so before use you must first import Avg, Max, Min, Count, Sum (capitalized) from django.db.models.
from django.db.models import Avg,Max,Min,Count,Sum # 引入函数
Return Value:
- After grouping, if you use values to get the values, the return value is a QuerySet data type containing dictionaries one by one;
- After grouping, if you use values_list to get the values, the return value is a QuerySet data type containing tuples one by one.
The limit in MySQL is equivalent to slicing of the QuerySet data type in ORM.
Note:
Put aggregate functions inside annotate.
-
values or values_list placed before annotate:values or values_list declare which fields to group by, and annotate performs the grouping.
-
values or values_list placed after annotate: annotate means grouping directly by the current table's pk, values or values_list indicate which fields to query, and you must give an alias to the aggregate function in annotate and write that alias in values or values_list.
Prepare data and create models
models.py
class
Emp
(
models.
Model
)
:
name
=
models.
CharField
(
max_length
=
32
)
age
=
models.
IntegerField
(
)
salary
=
models.
DecimalField
(
max_digits
=
8
,
decimal_places
=
2
)
dep
=
models.
CharField
(
max_length
=
32
)
province
=
models.
CharField
(
max_length
=
32
)
class
Emps
(
models.
Model
)
:
name
=
models.
CharField
(
max_length
=
32
)
age
=
models.
IntegerField
(
)
salary
=
models.
DecimalField
(
max_digits
=
8
,
decimal_places
=
2
)
dep
=
models.
ForeignKey
(
"Dep"
,
on_delete
=
models.
CASCADE
)
province
=
models.
CharField
(
max_length
=
32
)
class
Dep
(
models.
Model
)
:
title
=
models.
CharField
(
max_length
=
32
)
Data:
Execute in the MySQL command line:
INSERT
INTO
`
app01_emp
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
dep
`
,
`
province
`
)
VALUES
(
'
1
'
,
'
Linghu Chong
'
,
'
24
'
,
'
6000.00
'
,
'
Sales
'
,
'
Henan
'
)
;
INSERT
INTO
`
app01_emp
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
dep
`
,
`
province
`
)
VALUES
(
'
2
'
,
'
Ren Yingying
'
,
'
18
'
,
'
8000.00
'
,
'
Guangongbu
'
,
'
Guangdong
'
)
;
INSERT
INTO
`
app01_emp
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
dep
`
,
`
province
`
)
VALUES
(
'
3
'
,
'
Ren Woxing
'
,
'
56
'
,
'
10000.00
'
,
'
Sales
'
,
'
Guangdong
'
)
;
INSERT
INTO
`
app01_emp
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
dep
`
,
`
province
`
)
VALUES
(
'
4
'
,
'
Yue Lingshan
'
,
'
19
'
,
'
6000.00
'
,
'
Guangongbu
'
,
'
Henan
'
)
;
INSERT
INTO
`
app01_emp
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
dep
`
,
`
province
`
)
VALUES
(
'
5
'
,
'
Xiaolongnv
'
,
'
20
'
,
'
8000.00
'
,
'
Guangongbu
'
,
'
Hebei
'
)
;
INSERT
INTO
`
app01_dep
`
(
`
id
`
,
`
title
`
)
VALUES
(
'
1
'
,
'
Sales
'
)
;
INSERT
INTO
`
app01_dep
`
(
`
id
`
,
`
title
`
)
VALUES
(
'
2
'
,
'
Guangongbu
'
)
;
INSERT
INTO
`
app01_emps
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
province
`
,
`
dep_id
`
)
VALUES
(
'
2
'
,
'
Linghu Chong
'
,
'
24
'
,
'
8000.00
'
,
'
Henan
'
,
'
1
'
)
;
INSERT
INTO
`
app01_emps
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
province
`
,
`
dep_id
`
)
VALUES
(
'
3
'
,
'
Ren Yingying
'
,
'
18
'
,
'
9000.00
'
,
'
Guangdong
'
,
'
2
'
)
;
INSERT
INTO
`
app01_emps
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
province
`
,
`
dep_id
`
)
VALUES
(
'
4
'
,
'
Ren Woxing
'
,
'
57
'
,
'
10000.00
'
,
'
Guangdong
'
,
'
1
'
)
;
INSERT
INTO
`
app01_emps
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
province
`
,
`
dep_id
`
)
VALUES
(
'
5
'
,
'
Yue Lingshan
'
,
'
19
'
,
'
6000.00
'
,
'
Henan
'
,
'
2
'
)
;
INSERT
INTO
`
app01_emps
`
(
`
id
`
,
`
name
`
,
`
age
`
,
`
salary
`
,
`
province
`
,
`
dep_id
`
)
VALUES
(
'
6
'
,
'
Xiaolongnv
'
,
'
20
'
,
'
8000.00
'
,
'
Hebei
'
,
'
2
'
)
;
Calculate the price of the cheapest book for each publisher:
Example
res
=
models.
Publish
.
objects
.
values
(
"name"
)
.
annotate
(
in_price
=
Min
(
"book__price"
)
)
(
res
)
The following output can be seen in the command line:

Count the number of authors for each book:
Example
res
=
models.
Book
.
objects
.
annotate
(
c
=
Count
(
"authors__name"
)
)
.
values
(
"title"
,
"c"
)
(
res
)
The following output can be seen in the command line:

Count the number of authors for each book whose title starts with 'dish':
Example
res
=
models.
Book
.
objects
.
filter
(
title__startswith
=
"dish"
)
.
annotate
(
c
=
Count
(
"authors__name"
)
)
.
values
(
"title"
,
"c"
)
(
res
)

Count the names of books with more than one author:
Example
res
=
models.
Book
.
objects
.
annotate
(
c
=
Count
(
"authors__name"
)
)
.
filter
(
c__gt
=
0
)
.
values
(
"title"
,
"c"
)
(
res
)
The following output can be seen in the command line:

Sort the QuerySet in descending order by the number of authors of each book:
Example
res
=
models.
Book
.
objects
.
annotate
(
c
=
Count
(
"authors__name"
)
)
.
order_by
(
"-c"
)
.
values
(
"title"
,
"c"
)
(
res
)

Query the total price of books published by each author:
Example
res
=
models.
Author
.
objects
.
annotate
(
all
=
Sum
(
"book__price"
)
)
.
values
(
"name"
,
"all"
)
(
res
)

F() queries
An instance of F() can reference fields in a query to compare the values of two different fields in the same model instance.
The filters constructed before only compare field values with a constant; if you want to compare the values of two fields, you need to use F().
Before use, import F from django.db.models:
from django.db.models import F
Usage:
F("字段名称")
F dynamically obtains the value of an object's field and can perform operations.
Django supports addition, subtraction, multiplication, division, and modulo operations between F() objects and between F() objects and constants.
Modification operations (update) can also use the F() function.
Query people whose salary is greater than their age:
Example
from
django.
db
.
models
import
F
...
book
=
models.
Emp
.
objects
.
filter
(
salary__gt
=
F
(
"age"
)
)
.
values
(
"name"
,
"age"
)
...

Increase the price of every book by 100 yuan:
Example
res
=
models.
Book
.
objects
.
update
(
price
=
F
(
"price"
)
100
)
(
res
)

Q() queries
Before use, import Q from django.db.models:
from django.db.models import Q
Usage:
Q(条件判断)
For example:
Q(title__startswith="菜")
The relationships among multiple conditions in the filters constructed before are all and; if you need to perform more complex queries (such as or statements), you can use Q.
Q objects can be combined using the & | ~ (AND OR NOT) operators.
Precedence from high to low: ~ & |.
You can mix Q objects with keyword arguments; Q objects and keyword arguments are joined together with 'and' (i.e., treat the comma as and), but Q objects must be placed before all keyword arguments.
Query the name and price of books whose price is greater than 350 or whose name starts with 'dish'.
from django.db.models import Q
Example
...
res
=
models.
Book
.
objects
.
filter
(
Q
(
price__gt
=
350
)
|Q
(
title__startswith
=
"dish"
)
)
.
values
(
"title"
,
"price"
)
(
res
)
...

Query books ending with 'dish' or not from October 2010:
Example
res
=
models.
Book
.
objects
.
filter
(
Q
(
title__endswith
=
"dish"
)
|
~
Q
(
Q
(
pub_date__year
=
2010
)
& Q
(
pub_date__month
=
10
)
)
)
(
res
)

Query books whose publication date is 2004 or 1999 and whose title contains 'dish'.
Mixing Q objects with keyword arguments; Q objects must be before all keyword arguments:
Example
res
=
models.
Book
.
objects
.
filter
(
Q
(
pub_date__year
=
2004
)
| Q
(
pub_date__year
=
1999
)
,
title__contains
=
"dish"
)
(
res
)
