首页 > 代码库 > Django_Mysql数据表_创建

Django_Mysql数据表_创建

技术分享
class School(models.Model):
    class_teaher = models.OneToOneField(Teacher,unique=False)


class Teacher(models.Model):
    teacher = models.CharField(max_length=10)
一对一
技术分享
class School(models.Model):
    class_teaher = models.ForeignKey(Teacher,unique=False)
    class1 = models.CharField(max_length=10)
    class2 = models.CharField(max_length=10)


class Teacher(models.Model):
    teacher = models.CharField(max_length=10)
一对多
技术分享
#没有创建索引
class HostToGroup(models.Model):
    hgid = models.AutoField(primary_key=True)
    host_id = models.ForeignKey(Host)
    grou_id = models.ForeignKey(Group)
    
class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)

class Group(models.Model):
    gig = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
传统多对多
技术分享
class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)

class Group(models.Model):
    gig = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)

    h2g = models.ManyToManyField(Host)
   #django 自动帮我们创建第三张表 
django多对多
技术分享
class Host(models.Model):
    hid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32)
    ip = models.CharField(max_length=32)

class Group(models.Model):
    gig = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)

#基于第三张表的多对多 自定制强 推荐 默认没有做约束,
class HostToGroup(models.Model):
    hgid = models.AutoField(primary_key=True)
    host_id = models.ForeignKey(Host)
    group_id = models.ForeignKey(Group)
    status = models.IntegerField()
    
    #添加约束
    class Meta:
        #联合索引
        # index_together = ("host_id",‘goup_id‘)
        #联合唯一索引
        unique_together = [
            (host_id, group_id),]
多对多(自建第三张表)
技术分享
class single(models.Model):
    #自增id
    auto = models.AutoField(primary_key=True)
    #CharField 要求必须有一个参数 maxlength
    char = models.CharField(max_length=32,null=True)
    # 用于保存一个整数.
    ints = models.IntegerField(null=True)
    #一个带有检查 Email 合法性的 CharField,不接受 maxlength 参数.
    emal = models.EmailField(max_length=32,null=True)
    # 一个容量很大的文本字段.
    text = models.TextField(max_length=128,null=True)
    # 用于保存URL.若verify_exists参数为True(默认), 给定的URL会预先检查是否存在(即URL是否被有效装入且没有返回404响应).
    url = models.URLField(null=True)
    # #   日期格式      YYYY-MM-DD
    date = models.DateField(null=True)
    # #日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
    datetime = models.DateTimeField(null=True)
    # #时间格式      HH:MM[:ss[.uuuuuu]]
    time = models.TimeField(null=True)
    floats = models.FloatField()
    # decimal 必须加 max_digits 总位数  decimal_places 小数位数 而且总位数要大于等于小数位
    decimals = models.DecimalField(decimal_places=2,null=True,max_digits=10)
单表建立

 

Django_Mysql数据表_创建