首页 > 其他分享 >模型关联

模型关联

时间:2022-12-03 12:00:41浏览次数:44  
标签:name models 模型 db 关联 CharField class verbose

目录

一对多

  from django.db import models

  # Create your models here.

  class Project(models.Model):
      project_name = models.CharField(max_length=32,verbose_name="项目名称")
      project_describe = models.CharField(max_length=100,verbose_name="描述")
      project_create_date = models.DateTimeField(verbose_name="创建时间")

      class Meta: 
          db_table = 'db_project' # 给表定义表名

  class Clas(models.Model):
      SEX_CHOICES = (
          (0, "API"),
          (1, "WEBUI"),
          (2, "APPUI"),
      )

      cla_name = models.CharField(db_column="class_name",max_length=32,unique=True,verbose_name="姓名")
      cla_describe = models.CharField(db_column="class_describe",max_length=100,verbose_name="描述")
      cla_create_date = models.DateTimeField(db_column="class_create_date",verbose_name="创建时间")
      # 一对多 要将关联放在多的模型里面
      # db_column给字短定义名称 on_delete删除模式# db_constraint限制 下面这一行 他会在表中创建一个字短 “class_id”
      clas = models.ForeignKey(db_column="class_id",to="Project",on_delete=models.CASCADE,db_constraint=False)

      class Meta:
          db_table = 'db_class'

一对一

from django.db import models

# Create your models here.

class Project(models.Model):
    project_name = models.CharField(max_length=32,verbose_name="项目名称")

class Clas(models.Model):

    cla_name = models.CharField(db_column="class_name",max_length=32,unique=True,verbose_name="姓名")
    # 一对一 
    stu_detail = models.OneToOneField("StudentDetail",on_delete=models.CASCADE)

多对多

from django.db import models

# Create your models here.

class Project(models.Model):
    project_name = models.CharField(max_length=32,verbose_name="项目名称")

class Clas(models.Model):

    cla_name = models.CharField(db_column="class_name",max_length=32,unique=True,verbose_name="姓名")
    # 多对多 关联 放在两个模型里面哪个都可以 她会生成第三张表 默认表明是 类名_字段名 Clas_p 自定义表名 使用 db_table
    p = models.ManyToManyField("要关联的模型类名称",db_table="第三张表名")
    class Meta:
        db_table = 'db_class'    

标签:name,models,模型,db,关联,CharField,class,verbose
From: https://www.cnblogs.com/py-zhq/p/16940089.html

相关文章