以以下例子为基础做一些记录
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#班级主表(一)
class Clazz(models.Model):
cno = models.AutoField(primary_key=True)
cname = models.CharField(max_length=30)
#学生表(从表 多)
class Student(models.Model):
sno = models.AutoField(primary_key=True)
sname = models.CharField(max_length=30)
cno = models.ForeignKey(Clazz,on_delete=models.CASCADE,db_constraint=False)
def __unicode__(self):
return u'Student:%s'%self.sname
# insertData('wangwu','Oracle','MySQL')
class Course(models.Model):
course_no = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=30)
def __unicode__(self):
return u'Course:%s'%self.course_name
class Teacher(models.Model):
tno = models.AutoField(primary_key=True)
tname = models.CharField(max_length=30)
cour = models.ManyToManyField(Course,db_constraint=False)
def __unicode__(self):
return u'Teacher:%s'%self.tname
一对一:OneToOneField
一对多: ForeignKey
多对多 :ManyToManyField
参数 db_constraint=False 使用可以取消外键约束,
替代主键AutoField 自增的有限的替代方法是 uuid,
主要有2种方法 :
一是使用原生的UUID,
uuid:使用原生UUIDField,导入 import uuid
设置如下: sno=models.UUIDField(default = uuid.uuid4,auto_created = True,editable = False)
二是使用ShortUUIDField
安装 pip install django-shortuuidfield
需要导入 from shortuuidfield import ShortUUIDField
设置如下:
uid = ShortUUIDField(primary_key=True,auto_created = True)
###用例编号to_field 指向脚本实例用例编号,不要同时用db_constraint=False否则只能手动添加外键
|