Data preparation
from django.db import models # Create your models here. # Table app01_publish class Publish(models.Model): name = models.CharField(max_length=20) addr = models.CharField(max_length=20) # Table app01_authordetail class AuthorDetail(models.Model): tel = models.CharField(max_length=20) # Table app01_author class Author(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() # Table app01_author one to one table app01_authordetail detail = models.OneToOneField(to='AuthorDetail',to_field='id',unique=True,on_delete=models.CASCADE) # Table app01_book class Book(models.Model): title = models.CharField(max_length=20) price = models.DecimalField(max_digits=8, decimal_places=2) pub_date = models.DateField(auto_now_add=True) # Table app01_book many to one table app01_publish, parameter to specifies the model name, parameter to_field specifies the field to associate publish = models.ForeignKey(to='Publish',to_field='id',on_delete=models.CASCADE) # When we write our own sql, we need to create a new table for the many to many relationship between the book table and the author table. Based on django orm, the following line of code can help us automatically create that relationship table authors=models.ManyToManyField(to='Author') # If the variable name is authors, the new table name is app01_book_authors, if the variable name is XXX, the new table name is app01_book_xxx
As shown in the figure above Because of the foreign key, we need to implement app01_publish and app01_ Insert record in authordetail
# 1. Requirement: send to table app01 through model Publish_ Insert three publishers into the "Publish" Publish.objects.create(name='Beijing Publishing House') Publish.objects.create(name='Changchun Publishing House') Publish.objects.create(name='Dalian Publishing House') # 2. Requirement: send the model AuthorDetail to the table app01_ Insert three details of the author in the AuthorDetail AuthorDetail.objects.create(tel='12345678900') AuthorDetail.objects.create(tel='98765432100')
Multi table operation -- foreign key field
1. Increase
When inserting, multiple tables will be involved. We will also introduce them in three cases
Use the create() method for one-to-one and one to many relationships and the add() method for many to many relationships
Demand: books (sunflower classic, chrysanthemum classic, peach blossom Classic) are all published in Beijing Publishing House
Many to one
# Line through magic heart Publish from the press table app01_ Find out the Beijing Publishing House publish_obj = Publish.objects.filter(name='Beijing Publishing House').first()
Method 1: use publish_ The ID parameter specifies the association
If there is a Publisher id, you can specify it directly
models.Book.objects.create(title='Sunflower classic',price=200,publish_id=1) models.Book.objects.create(title='Chrysanthemum classic', price=3000, publish_id=1) models.Book.objects.create(title='Peach blossom classic', price=4000, publish_id=1)
Method 2: use the publish parameter to specify the Association
For the foreign key field, you can also directly pass in the foreign key object you want to associate, but the field name is not the field name in the table, but the name of the table you want to link
models.Book.objects.create(title='Romance of the Three Kingdoms',price='123.99',publish=publish_obj)
one-on-one
Requirement: insert three authors and make one-to-one correspondence in the author details table
Note: the one-to-one dictionary is unique and cannot be repeated
# Method 1: it is required to filter out the object of author details in advance, and then specify the author details object to be associated through the field author of the model author author_obj1 = Author.objects.filter(pk=1) Author.objects.create(name='egon',age=18,author = author_obj1) ...# The rest are omitted # Method 2: determine the id of the Author detail object, and then use the model Author and the field author_id to specify the association relationship, Author.objects.create(name='egon',age=18,author_detail_id=1) Author.objects.create(name='kevin',age=38,author_detail_id=2) Author.objects.create(name='rose',age=28,author_detail_id=3)
Many to many
add() method
Note: for the virtual field corresponding to the ManyToMAnyField created in that table, use the add() method of that table
Method 1: add according to object
In native sql, the many to many relationship involves operating the table relationship in Chapter 3, but in ORM, we only need to operate the field author under the model class Book
# 1. Get book object first book_obj1=Book.objects.get(title='Sunflower classic') # 2. Then get the author object lili=Author.objects.get(name='lili') frank=Author.objects.get(name='frank') # 3. Finally, create the above relationships in turn: book_obj1.authors.add(lili,frank)
Method 2: directly transfer in the primary key value
book_obj1=Book.objects.get(title='Chrysanthemum classic') book_obj1.authors.add(1) book_obj1=Book.objects.get(title='Peach blossom classic') book_obj1.authors.add(1,4)
change
One to many, one-on-one
update() method
There are also two methods: pass in the modified field or an object
# Method 1: Book.objects.filter(title='Romance of the Three Kingdoms').update(publish_id=2) # Mode 2: publish_obj = Publish.objects.filter(pk=2).first .objects.filter(title='Romance of the Three Kingdoms').update(publish=publish_obj)
Many to many
set() method
For this method, what needs to be passed in parentheses is an iterative object
It should be noted that the virtual field corresponding to the ManyToManyField created in that table, then use the add() method of that table
Method 1: add according to object
# 1. Get book object first book_obj1=Book.objects.get(title='Sunflower classic') # 2. Then get the author object lili=Author.objects.get(name='lili') frank=Author.objects.get(name='frank') # 3. Finally, modify the above relationship: book_obj1.authors.set([lili,frank])
Method 2: directly transfer in the primary key value
book_obj1=Book.objects.get(title='Chrysanthemum classic') book_obj1.authors.set([2,1])
delete
One to many, one to one
django1.x foreign key fields are deleted cascade by default. For versions 2.x and above, you need to specify on yourself_ Delete field
Publish.objects.filter(pk=3).delete() # If the Publishing House Table deletes the book with the primary key of 3, the book with the publishing house ID of 3 in the book table will also be deleted
Many to many
remove() method
This method can delete one or more
Method 1: delete by object
# 1. Get book object first book_obj1=Book.objects.get(title='Sunflower classic') # 2. Then get the author object lili=Author.objects.get(name='lili') frank=Author.objects.get(name='frank') # 3. Finally, modify the above relationship: book_obj1.authors.remove([lili,frank])
Method 2: directly transfer in the primary key value
book_obj1=Book.objects.get(title='Chrysanthemum classic') book_obj1.authors.remove([2,1])
clear() method
This method is used for emptying
book_obj1=Book.objects.get(title='Chrysanthemum classic') book_obj1.authors.clear()
Foreign key field operation summary
One to one relationship, The one-to-many relationship is like this. Find the table where the foreign key field is located, and then operate according to the table
Many to many table operations You need to find the table where the foreign key field is located first, then determine the field in another table that needs to be operated, and finally wipe the total according to the table where the foreign key field is located, and the methods used for operation are different