This article will talk about setting foreign key operation , More about foreign keys , You can look at the knowledge of the database . Of course, I will still make some explanations in the notes .
Now we have the list of publishers , Now let's add the book table . Because there is a relationship between publishing houses and books , We use foreign keys to connect the two . stay models.py Is as follows ：
from django.db import models # Create your models here. """ There is a relationship between books and publishers . The book is published by a publishing house . For example, the Mechanical Industry Press published 《 Data structure and algorithm analysis ——C Language description 》 This book . that , The list of publishers below us needs to have a relationship with the list of books , A publishing house can publish more than one book . """ class Publisher(models.Model): """ Django Of models The primary key will be created in the database by default """ name = models.CharField(max_length=128) # Publisher name class Book(models.Model): name = models.CharField(max_length=128) # Title publisher_id = models.ForeignKey('Publisher', on_delete=models.CASCADE) # By default, foreign keys are associated with Publisher Primary Key . ''' ForeignKey The first parameter of is the class name of the table to be associated with , You can write the class name directly , But this time it must be the class defined in the previous article . You can also change the class name into a string , In this way, the class is not required to be defined in the previous article . The second parameter on_delete stay Django2.0 It must be filled in after that ,models.CASCADE Indicates cascade delete . Cascade deletion means , I deleted a publishing house , Then all the books corresponding to the publishing house have also been deleted . models.PROTECT: Protect , If a publishing house still has books , Then it is not allowed to delete the publishing house . models.SET_DEFAULT: It means to set it as the default value after deletion models.SET_NULL: Set to null after deletion models.SET(x): Set to a certain value after deletion '''
After adding a table , We should execute the database migration command . As shown in the figure below .
This completes the migration of the database . after , You will find that the structure of the table is as follows .
publisher_id_id It's a strange name , This is because models Will automatically add _id This suffix , therefore , Modify our Book The categories are as follows ：
class Book(models.Model): name = models.CharField(max_length=128) # Title publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE)
Revised models after , The database migration command must be re executed .
After database migration , As shown below ：
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .