Table realization of the relationship between django

1, three kinds of relationship correspondence relationship table in the Model class

 

 2, student tables, student specific information table, table School, the curriculum, for example to achieve the three relationships between tables

Analysis: There are more than a college student, and therefore the relationship between college students for many relationship

     A multi-course student, a course has on more than one student, so the relationship between students and course-many relationship

     A student has a specific information table, information table corresponds to a specific student, so students and student specific information table is one to one relationship

 

 3, code implementation

from django.db import models


# Create your models here.
class Department(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)

    def __str__(self):
        return f"Department({self.id}, {self.name})"


class Student(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20)
    department = models.ForeignKey("Department", on_delete=models.CASCADE)
    course = models.ManyToManyField("Course")

    def __str__(self):
        return f"Student({self.id}, {self.name})"


class StudentDetail(models.Model):
    _id = models.OneToOneField("Student", on_delete=models.CASCADE)
    age = models.IntegerField()
    

    def __str__(self):
        return f"StudentDetail({self.id}, {self.age})"


class Course(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)

    def __str__(self):
        return f"Course({self.id}, {self.age})"

4、数据库的表现形式

 

 

 

        数据库与代码比较后发现,一个Model类中,一个字段如果是关联字段,在创建数据表时,会在该字段后面,默认加上“_id”,当然,由于多对多是通过主键+联合唯一实现的,就需要创建第三张表,因而在数据库对应的学生表中,没有其创建的与课程有关的字段。

5、补充

  • 三种表关系models.OneToOneField、models.ForeignKey、models.ManyToManyField的第一个参数为所关系的表名(字符串名和类名都可以),但是要注意,如果是类名,所关联的类名必须在本类前面,否则就会报错,建议使用字符串名
  • on_delete参数:为了告知当所关联的表被删除后,如何处理:
  • on_delete=None, # 删除关联表中的数据时,当前表与其关联的field的行为
    • on_delete=models.CASCADE, # 删除关联数据,与之关联也删除

    • on_delete=models.DO_NOTHING, # 删除关联数据,什么也不做

    • on_delete=models.PROTECT, # 删除关联数据,引发错误ProtectedError

    • on_delete=models.SET_NULL, # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理)

    • on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理)

    • on_delete=models.SET, # 删除关联数据,
           a. 与之关联的值设置为指定值,设置:models.SET(值)
           b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

 

Guess you like

Origin www.cnblogs.com/loveprogramme/p/12404144.html