Django ORM – Multi-Table Examples
The relationships between tables can be divided into the following three types:
- One-to-one: One person corresponds to one ID card number; set the data field to unique.
- One-to-many: One family has multiple people, generally implemented through a foreign key.
- Many-to-many: One student has multiple courses, and one course has many students, generally implemented through a third table to establish the association.

Create the model
Next let's look at multi-table multiple instances.
Example
class
Book
(
models.
Model
)
:
title
=
models.
CharField
(
max_length
=
32
)
price
=
models.
DecimalField
(
max_digits
=
5
,
decimal_places
=
2
)
pub_date
=
models.
DateField
(
)
publish
=
models.
ForeignKey
(
"Publish"
,
on_delete
=
models.
CASCADE
)
authors
=
models.
ManyToManyField
(
"Author"
)
class
Publish
(
models.
Model
)
:
name
=
models.
CharField
(
max_length
=
32
)
city
=
models.
CharField
(
max_length
=
64
)
=
models.
EmailField
(
)
class
Author
(
models.
Model
)
:
name
=
models.
CharField
(
max_length
=
32
)
age
=
models.
SmallIntegerField
(
)
au_detail
=
models.
OneToOneField
(
"AuthorDetail"
,
on_delete
=
models.
CASCADE
)
class
AuthorDetail
(
models.
Model
)
:
gender_choices
=
(
(
0
,
"female"
)
,
(
1
,
"male"
)
,
(
2
,
"confidential"
)
,
)
gender
=
models.
SmallIntegerField
(
choices
=
gender_choices
)
tel
=
models.
CharField
(
max_length
=
32
)
addr
=
models.
CharField
(
max_length
=
64
)
birthday
=
models.
DateField
(
)
Explanation:
- 1. The EmailField data type is in email format; it inherits from CharField at the bottom and is wrapped, equivalent to varchar in MySQL.
- 2. Django version 1.1 does not need cascading delete: on_delete=models.CASCADE; Django 2.2 does.
- 3. Generally there is no need to set cascading update.
- 4. The foreign key is set on the 'many' side of one-to-many: models.ForeignKey("related class name", on_delete=models.CASCADE).
- 5. OneToOneField = ForeignKey(..., unique=True) sets one-to-one.
- 6. If a model class has a foreign key, when creating data you must first create the data of the model class associated by the foreign key; otherwise, when creating data of the model class containing the foreign key, the data of the associated model class of the foreign key will not be found.
Table Structure
Book table Book: title, price, pub_date, publish (foreign key, many-to-one), authors (many-to-many)
Publisher table Publish:name 、 city 、 email
Author table Author: name, age, au_detail (one-to-one)
Author details table AuthorDetail:gender 、 tel 、 addr 、 birthday
The following is the table association description:
Insert data
We execute the following SQL insert operations in MySQL:
insert into app01_publish(name,city,email) values ("华山出版社", "华山", "hs@163.com"), ("明教出版社", "黑木崖", "mj@163.com")
# First insert multiple data into authordetail table
insert into app01_authordetail(gender,tel,addr,birthday) values (1,13432335433,"华山","1994-5-23"), (1,13943454554,"黑木崖","1961-8-13"), (0,13878934322,"黑木崖","1996-5-20")
# Then insert the data into author, so author can find authordetail
insert into app01_author(name,age,au_detail_id) values ("令狐冲",25,1), ("任我行",58,2), ("任盈盈",23,3)

ORM - Adding Data
One-to-many (foreign key ForeignKey)
Method 1: Passing an object; the return value's data type is an object, a book object.
Steps:
- a. Get the publisher object
- b. Pass the publisher object to the book's publisher attribute pulish
app01/views.py file code:
def
add_book
(
request
)
:
Get the publisher object
pub_obj
=
models.
Publish
.
objects
.
filter
(
pk
=
1
)
.
first
(
)
Pass the publisher object to the book's publisher attribute publish
book
=
models.
Book
.
objects
.
create
(
title
=
"Runoob Tutorial"
,
price
=
200
,
pub_date
=
"2010-10-10"
,
publish
=
pub_obj
)
(
book
,
type
(
book
)
)
return
HttpResponse
(
book
)

Method 2: Passing the object's id form (since the data passed is generally an id, passing the object id is commonly used).
In one-to-many, in the class that sets the foreign key attribute (the 'many' table), the field name shown in MySQL is:foreign key attribute name_id。
The return value's data type is an object, a book object.
Steps:
- a. Get the id of the publisher object
- b. Pass the id of the publisher object to the book's associated publisher field pulish_id
app01/views.py file code:
def
add_book
(
request
)
:
Get the publisher object
pub_obj
=
models.
Publish
.
objects
.
filter
(
pk
=
1
)
.
first
(
)
Get the id of the publisher object
pk
=
pub_obj.
pk
Pass the id of the publisher object to the book's associated publisher field publish_id
book
=
models.
Book
.
objects
.
create
(
title
=
"Chongling Jianfa"
,
price
=
100
,
pub_date
=
"2004-04-04"
,
publish_id
=
pk
)
(
book
,
type
(
book
)
)
return
HttpResponse
(
book
)

Many-to-many (ManyToManyField): adding data in the third relation table
Method 1: Passing object form, no return value.
Steps:
- a. Get the author object
- b. Get the book object
- c. Use the add method to pass the author object to the book object's authors attribute
app01/views.py file code:
def
add_book
(
request
)
:
Get the author object
chong
=
models.
Author
.
objects
.
filter
(
name
=
"Linghu Chong"
)
.
first
(
)
ying
=
models.
Author
.
objects
.
filter
(
name
=
"Ren Yingying"
)
.
first
(
)
Get the book object
book
=
models.
Book
.
objects
.
filter
(
title
=
"Runoob Tutorial"
)
.
first
(
)
Use the add method to pass the author object to the book object's authors attribute
book.
authors
.
add
(
chong
,
ying
)
return
HttpResponse
(
book
)

Method 2: Passing object id form, no return value.
Steps:
- a. Get the id of the author object
- b. Get the book object
- c. Use the add method to pass the id of the author object to the book object's authors attribute
app01/views.py file code:
def
add_book
(
request
)
:
Get the author object
chong
=
models.
Author
.
objects
.
filter
(
name
=
"Linghu Chong"
)
.
first
(
)
Get the id of the author object
pk
=
chong.
pk
Get the book object
book
=
models.
Book
.
objects
.
filter
(
title
=
"Chongling Jianfa"
)
.
first
(
)
Use the add method to pass the id of the author object to the book object's authors attribute
book.
authors
.
add
(
pk
)

Related manager (object call)
Prerequisites:
- Many-to-many (both directions have a related manager)
- One-to-many (only the objects of the 'many' class have a related manager, i.e., only in the reverse direction)
Syntax format:
正向:属性名
反向:小写类名加 _set
**Note:** One-to-many can only be reverse
Common methods:
add(): Used for many-to-many, adding the specified model object to the related object set (relation table).
**Note:** add() in one-to-many (i.e., foreign key) can only pass objects ( QuerySet data type), not id ([id table]).
*[ ] usage:
Method 1: Pass objects
book_obj
=
models.
Book
.
objects
.
get
(
id
=
10
)
author_list
=
models.
Author
.
objects
.
filter
(
id__gt
=
2
)
book_obj.
authors
.
add
(
*author_list
)
Add author objects with id greater than 2 to this book's author set
Method 2: Pass object ids
book_obj.
authors
.
add
(
[
1
,
3
]
)
Add author objects with id=1 and id=3 to this book's author set
return
HttpResponse
(
"ok"
)

Reverse: lowercase table name_set
ying
=
models.
Author
.
objects
.
filter
(
name
=
"Ren Yingying"
)
.
first
(
)
book
=
models.
Book
.
objects
.
filter
(
title
=
"Chongling Jianfa"
)
.
first
(
)
ying.
book_set
.
add
(
book
)
return
HttpResponse
(
"ok"
)

create(): Create a new object and simultaneously add it to the related object set.
Return the newly created object.
pub
=
models.
Publish
.
objects
.
filter
(
name
=
"Mingjiao Press"
)
.
first
(
)
wo
=
models.
Author
.
objects
.
filter
(
name
=
"Ren Woxing"
)
.
first
(
)
book
=
wo.
book_set
.
create
(
title
=
"Xixing Dafa"
,
price
=
300
,
pub_date
=
"1999-9-19"
,
publish
=
pub
)
(
book
,
type
(
book
)
)
return
HttpResponse
(
"ok"
)

remove(): Remove the specified model object from the related object set.
For ForeignKey objects, this method exists only when null=True (can be empty), with no return value.
Example
author_obj
=
models.
Author
.
objects
.
get
(
id
=
1
)
book_obj
=
models.
Book
.
objects
.
get
(
id
=
11
)
author_obj.
book_set
.
remove
(
book_obj
)
return
HttpResponse
(
"ok"
)

clear(): Remove all objects from the related object set, delete the association, but do not delete the objects.
For ForeignKey objects, this method exists only when null=True (can be empty).
No return value.
Clear all authors associated with Dugu Jiujian
book
=
models.
Book
.
objects
.
filter
(
title
=
"Runoob Tutorial"
)
.
first
(
)
book.
authors
.
clear
(
)
ORM Queries
Object-based cross-table queries.
正向:属性名称
反向:小写类名_set
One-to-many
Query the city where the publisher of the book with primary key 1 is located (forward).
Example
book
=
models.
Book
.
objects
.
filter
(
pk
=
10
)
.
first
(
)
res
=
book.
publish
.
city
(
res
,
type
(
res
)
)
return
HttpResponse
(
"ok"
)

Query the names of books published by Mingjiao Press (reverse).
Reverse: object.lowercase class name_set (pub.book_set) can jump to the associated table (book table).
pub.book_set.all(): Take all book objects from the book table and, within a QuerySet, iterate to retrieve book objects one by one.
Example
pub
=
models.
Publish
.
objects
.
filter
(
name
=
"Mingjiao Press"
)
.
first
(
)
res
=
pub.
book_set
.
all
(
)
for
i
in
res:
(
i.
title
)
return
HttpResponse
(
"ok"
)

One-to-one
Query Linghu Chong's phone number (forward)
Forward: object.attribute (author.au_detail) can jump to the associated table (author details table)
Example
author
=
models.
Author
.
objects
.
filter
(
name
=
"Linghu Chong"
)
.
first
(
)
res
=
author.
au_detail
.
tel
(
res
,
type
(
res
)
)
return
HttpResponse
(
"ok"
)

Query the names of all authors whose address is in Heimuya (reverse).
For one-to-one reverse, use object.lowercase class name and that's enough; no need to add _set.
Reverse: object.lowercase class name (addr.author) can jump to the associated table (author table).
Example
addr
=
models.
AuthorDetail
.
objects
.
filter
(
addr
=
"Heimuya"
)
.
first
(
)
res
=
addr.
author
.
name
(
res
,
type
(
res
)
)
return
HttpResponse
(
"ok"
)

Many-to-many
Runoob Tutorial all authors' names and phone numbers (forward).
Forward: **object.attribute (book.authors)** can jump to the associated table (author table).
The author table has no author phone number, so again through **object.attribute (i.au_detail)** jump to the associated table (author details table).
Example
book
=
models.
Book
.
objects
.
filter
(
title
=
"Runoob Tutorial"
)
.
first
(
)
res
=
book.
authors
.
all
(
)
for
i
in
res:
(
i.
name
,
i.
au_detail
.
tel
)
return
HttpResponse
(
"ok"
)

Query the names of all books published by Ren Woxing (reverse).
Example
author
=
models.
Author
.
objects
.
filter
(
name
=
"Ren Woxing"
)
.
first
(
)
res
=
author.
book_set
.
all
(
)
for
i
in
res:
(
i.
title
)
return
HttpResponse
(
"ok"
)

Double-underscore-based cross-table queries
Forward: attribute_name__cross-table attribute_name Reverse: lowercase_class_name__cross-table attribute_name
One-to-many
Query the names and prices of all books published by Cainiao Press.
Example
res
=
models.
Book
.
objects
.
filter
(
publish__name
=
"Cainiao Press"
)
.
values_list
(
"title"
,
"price"
)

Reverse: through lowercase class name__cross-table attribute name (book__title, book__price) Cross-table data retrieval.
Example
res
=
models.
Publish
.
objects
.
filter
(
name
=
"Cainiao Press"
)
.
values_list
(
"book__title"
,
"book__price"
)
return
HttpResponse
(
"ok"
)

Many-to-many
Query the names of all books published by Ren Woxing.
Forward: through attribute_name__cross-table attribute name (authors__name) to retrieve data across tables:
res = models.Book.objects.filter(authors__name="Ren Woxing").values_list("title")
Reverse: through lowercase class name__cross-table attribute name (book__title) to retrieve data across tables:
res = models.Author.objects.filter(name="Ren Woxing").values_list("book__title")

One-to-one
Query Ren Woxing's phone number.
Forward: through **attribute_name__cross-table attribute name (au_detail__tel) ** retrieve data across tables.
res = models.Author.objects.filter(name="Ren Woxing").values_list("au_detail__tel")

Reverse: through **lowercase class name__cross-table attribute name (author__name) ** retrieve data across tables.
res = models.AuthorDetail.objects.filter(author__name="Ren Woxing").values_list("tel")

