创建如下几张表
from django.shortcuts import HttpResponse, render, redirect
from django.db import models
class Class(models.Model):
id = models.AutoField(primary_key=True)
cname = models.CharField(max_length=32)
cdata = models.DateField()
def __str__(self):
return "%s" % [self.__class__, self.cname]
class Student(models.Model):
id = models.AutoField(primary_key=True)
sname = models.CharField(max_length=32)
# 一对多
# cid = models.ForeignKey(to="Class",to_field="id",related_name="student")
cid = models.ForeignKey(to="Class", to_field="id")
# 一对一
detail = models.OneToOneField("StudentDetail", to_field="id")
# 等同于如下的代码
# detail = models.ForeignKey(to="StudentDetail",to_field="id",unique=True)
def __str__(self):
return "%s" % [self.sname]
# #建立多对多 第一种方法
# class Teacher(models.Model):
# id = models.AutoField(primary_key=True)
# tname = models.CharField(max_length=32)
#
#
# class Teacher2Class(models.Model):m
# id = models.AutoField(primary_key=True)
# tid = models.ForeignKey(to="Teacher",to_field="id")
# cid = models.ForeignKey(to="Class",to_field="id")
#
# class Meta:
# unique_together = ("tid","cid")
# 建立多对多 第二种方法
class Teacher(models.Model):
id = models.AutoField(primary_key=True)
tname = models.CharField(max_length=32)
cid = models.ManyToManyField(to="Class",name="teacher")
# 建立多对多 第3种方法
# class Teacher(models.Model):
# id = models.AutoField(primary_key=True)
# tname = models.CharField(max_length=32)
# cid_tid = models.ManyToManyField(to="Class",
# through="Teacher2Class",
# through_fields=("tid", "cid"))
#
# class Teacher2Class(models.Model):
# id = models.AutoField(primary_key=True)
# tid = models.ForeignKey(to="Teacher", to_field="id")
# cid = models.ForeignKey(to="Class", to_field="id")
#
# class Meta:
# unique_together = ("tid", "cid")
class StudentDetail(models.Model):
id = models.AutoField(primary_key=True)
height = models.PositiveIntegerField()
email = models.EmailField()
memo = models.CharField(max_length=128)
需要注意的如下:
# 一对多
# cid = models.ForeignKey(to="Class",to_field="id",related_name="student")
cid = models.ForeignKey(to="Class", to_field="id")
# 一对一
detail = models.OneToOneField("StudentDetail", to_field="id")
# 等同于如下的代码
# detail = models.ForeignKey(to="StudentDetail",to_field="id",unique=True)
以上的app01_teacher2class表是通过第3种方法创建的,我们来看下第一种、第二方法创建的表名、字段名是怎样的?
通过方法2 创建班级-老师对应表如下:
正向查询(由学生信息表查询学生详情表)
stu = models.Student.objects.first()
stu.detail.email
'1@qq'
反向查询(由学生详情表反向查询学生信息表)
detail = models.StudentDetail.objects.get(id=1)
detail.student.sname
'小一
正向查询(由学生表查询班级表)
from app01 import models
stu = models.Student.objects.first()
stu.cid_id
1
stu.cid.cname
'全栈1期'
反向查询(由班级表查询学生表)
cls = models.Class.objects.first()
cls.student_set.all()
: ['小一']>, '小二' ]>]>
注意:
如果不在外键的字段中设置related_name的话,默认就用表名_set。
如果设置了related_name=”students”,反向查询时可直接使用students进行反向查询。
cls.students.all()
正向查询(由老师表查询班级表)
from app01 import models
tea = models.Teacher.objects.first()
tea.cid_tid
.ManyRelatedManager object at 0x05C110F0>
tea.cid_tid.all()
'app01.models.Class'>, '全栈1期']>, 'app01.models.Class'>, '全栈2期']>]>
first = tea.cid_tid.first()
first
'app01.models.Class'>, '全栈1期']>
first.cname
'全栈1期'
first.student_set
.RelatedManager object at 0x03283870>
first.student_set.all()
'小一']>, '小二']>]>
反向查询(由班级表反向查询老师表)
cls = models.Class.objects.first()
cls.student_set
.RelatedManager object at 0x03283070>
cls.teacher_set
.ManyRelatedManager object at 0x03224710>
cls.teacher_set.all()
object>, object>]>
cls.teacher_set.all().first()
object>
cls.teacher_set.all().first().cid_tid
.ManyRelatedManager object at 0x032A2790>
cls.teacher_set.all().first().tname
'王老师'
create()
from app01 import models
import datetime
teacher = models.Teacher.objects.get(id=1)
teacher.cid.create(cname="linux2",cdata=datetime.datetime.now())
'app01.models.Class'>, 'linux2']>
多对对
cls = models.Class.objects.get(id=1)
cls.teacher_set.create(tname="egon")
import datetime
cls = models.Class.objects.first()
cls.student_set.create(sname="王七",detail_id=4)
stu = models.Student.objects.create(sname="wyf",detail_id=5,cid_id=2)
add()
from app01 import models
import datetime
cls = models.Class.objects.all()
models.Teacher.objects.first().cid.add(*cls)
set\remove\clear
tea = models.Teacher.objects.first()
tea.cid.set([4,3])
tea.cid.remove(3)
tea.cid.clear()
models.Class.objects.filter(student__sname__contains="d")
<QuerySet [<Class: [<class 'app01.models.Class'>, 'python']>, <Class: [<class 'app01.models.Class'>, 'sfsdf']>]>
models.Class.objects.values("cname")
'cname': 'linux'}, {'cname': 'python'}, {'cname': 'sfsdf'}]>
models.Class.objects.values("cname","student__sname")
'cname': 'linux', 'student__sname': 'wyf'}, {'cname': 'python', 'student__sname': 'wfdsd'}, {'cname': 'sfsdf', 'student__sname': 'fdgerter'}]>
以下方法不可行!!
models.Class.objects.first().values("cname","student__sname")
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Class' object has no attribute 'values'
models.Class.objects.all().values("cname","student__detail__email")
'cname': 'linux', 'student__detail__email': '1@qq'}, {'cname': 'python', 'student__detail__email': '2@werwe'}, {'cname': 'sfsdf', 'student__detail__email': '4@fds'}, {'cname': 'linux', 'student__detail__email': '2@werw'}]>