知识要点:
表关系的实现
一对多表关系
在Mysql中一对多是通过外键实现的,在django模型中通过ForeignKeyfield类型实现。
一对一表关系
在Mysql中一对一是通过外键加唯一键实现的,在django模型中通过OneToOneField类型实现。
多对多表关系
在Mysql中多对多是通过中间表外键加联合唯一键实现的,在django模型中通过ManyToManyField类型实现。中间表模型会自动帮我们创建好。
例子:
class Department(models.Model):
d_id = models.AutoField(primary_key=True)
d_name = models.CharField(max_length=30)
def __str__(self):
return 'Department<d_id=%s,d_name=%s>'%(
self.d_id,self.d_name
)
class Student(models.Model):
s_id = models.AutoField(primary_key=True)
s_name = models.CharField(max_length=30)
department = models.ForeignKey('Department')
course = models.ManyToManyField('Course')
def __str__(self):
return 'Student<s_id=%s,s_name=%s>'%(
self.s_id,self.s_name
)
class Course(models.Model):
c_id = models.AutoField(primary_key=True)
c_name = models.CharField(max_length=30)
def __str__(self):
return 'Course<c_id=%s,c_name=%s>'%(
self.c_id,self.c_name
)
class Stu_detail(models.Model):
s_id = models.OneToOneField('Student')
age = models.IntegerField()
gender = models.BooleanField(default=1)
country = models.CharField(max_length=30,null=True)
def __str__(self):
return 'Stu_detail<s_id=%s,age=%s,gender=%s,country=%s>'%(
self.s_id,self.age,self.gender,self.country
)
关系表中数据的操作
from .models import Department,Student,Course
def add_info(request):
# d1 = Department(d_name='CC')
# d1.save()
# 一对多关系加内容
# s1 = Student(s_name='xiaoming')
# s1.department = d1
# s1.save()
# 多对多关系添加内容
# c1 = Course(c_name='python')
# s1 = Student.objects.first()
# c1.save()
# s1.course.add(c1)
return HttpResponse('添加数据成功')
def search_info(request):
rs = Student.objects.all()[0]
# 一对多的查询
print(rs.department)
# 多对多的正向查询
print(rs.course.all())
cs = Course.objects.first()
# 多对多反向查询
print(cs.student_set.all())
return HttpResponse('查询数据成功')