Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django ORM – Multi-Table Examples

Django ORM – Multi-Table Examples

The relationships between tables can be divided into the following three types:

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

)

   

email

=

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:

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:

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

)

   

print

(

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:

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

)

   

print

(

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:

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:

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:

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

)

print

(

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

print

(

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:

   

print

(

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

print

(

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

print

(

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:

   

print

(

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:

   

print

(

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")