主要知识点:
model.py
from django.db import models
from datetime import datetime
# 拓展表
class StudentInfo(models.Model):
phone = models.CharField(max_length=11, null=True, unique=True, verbose_name='电话')
address = models.CharField(max_length=50, null=True, verbose_name='地址')
class Meta:
db_table = 'student_info'
class Grade(models.Model):
g_name = models.CharField(max_length=10, unique=True, verbose_name='班级名')
class Meta:
db_table = 'grade'
class Course(models.Model):
c_name=models.CharField(max_length=10,null=True,verbose_name='课程名')
class Meta:
db_table='course'
class Student(models.Model):
s_name = models.CharField(max_length=10, unique=True, verbose_name='姓名')
s_age = models.IntegerField(default=16, verbose_name='年龄')
s_sex = models.BooleanField(default=1, verbose_name='性别')
creat_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
operate_time = models.DateTimeField(auto_now=True, verbose_name='修改时间')
# 数学成绩
math = models.DecimalField(max_digits=4, decimal_places=2, null=True)
# 语文成绩
chinese = models.DecimalField(max_digits=4, decimal_places=2, null=True)
# 关联关系
# 一对一
stu_info = models.OneToOneField(StudentInfo, null=True,related_name='stud')
# 一对多
g=models.ForeignKey(Grade,null=True,related_name='stud')
# 多对多
c=models.ManyToManyField(Course,null=True)
# def __init__(self, name, age=None, sex=None):
# super().__init__()
# self.s_name=name
# self.s_age=age if age else self.s_age
# self.s_sex=sex if sex else self.s_sex
# # 创建时间
# self.creat_time=datetime.now()
# self.operate_time=datetime.now()
class Meta:
db_table='student'
urls.py
from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('create_stu/',views.create_stu),
url('select_stu/',views.select_stu),
url('delete_stu/',views.delete_stu),
url('update_stu/',views.update_stu),
url('create_stu_info/',views.create_stu_info),
url('stu_add_stu_info/',views.stu_add_stu_info),
url('sel_phone_by_stu',views.sel_phone_by_stu),
url('sel_stu_by_phone',views.sel_stu_by_phone),
url('create_grade',views.create_grade),
url('stu_add_grade',views.stu_add_grade),
url('sel_stu_by_grade',views.sel_stu_by_grade),
url('sel_grade_by_stu',views.sel_grade_by_stu),
url('create_course',views.create_course),
url('create_stu_course',views.create_stu_course),
url('sel_course_by_stu',views.sel_course_by_stu),
url('sel_stu_by_course',views.sel_stu_by_course),
]
views.py
from django.db.models import F, Avg, Q
from django.http import HttpResponse
from django.shortcuts import render
from app.models import Student, StudentInfo, Grade, Course
def create_stu(request):
# 创建学生信息
# 引入ORM概念:对象关系映射 insert into student value()
# 第一种
# Student.objects.create(s_name='晓晓')
# 第二种
# stu=Student()
# stu.s_name='小坑'
# stu.save()
# 第三种(尽量少用,问题很多)
# stu=Student('小菜',20,0)
# stu.save()
return HttpResponse('创建学生方法')
def select_stu(request):
'''
查询数据
all :查询所有数据
filter:获取的结果为queryset(查询集),结果可以返回空,一个或多个对象
get() 获取的结果为object(单个)对象,如果没有满足条件的对象获取会报错,获取的对象超过一个也会报错
注意:get()能不用就不用,最后就不要用
exclude :不包含 获取不包含该对象以外的所有对象
order_by :排序 +:升序 -:降序
values-->获取单个字段
first:获取queryset(查询集)中的第一个对象
last:获取queryset(查询集)中的最后一个对象
切片--->前面那个下标要考虑取值范围,后面那个不用
模糊查询:contains==>'%x%' startswith==>'x%' endswith==>'%x'
isnull/isnotnull 判断是否为空/是否不为空
in 判断在范围之内
pk:与主键功能相同
比较运算:gt(大于) gte(大于等于) lt(小于) lte(小于等于)
逻辑运算:Q(条件) | Q(条件) 逻辑或 ;Q(条件) & Q(条件) 逻辑与 ;~Q(条件) 逻辑非
'''
# all :所有
# select * from student;
# stus=Student.objects.all()
# filter:获取的结果为queryset,可以返回空,一条或多条
# select * from student where s_name='小李'
# stus=Student.objects.filter(s_name='小李')
# 查询年龄等于16,年龄不存在时,结果空
# stus=Student.objects.filter(s_age=16)
# get() 获取的结果为object对象,获取不成功会报错,结果超过一条也会报错
# 获取年龄等于20的学生,获取对象时,如果满足的对象超过一个会报错
# stus=Student.objects.get(s_age=18)
# stus=Student.objects.get(id=100)
# 查询多条
# stus=Student.objects.filter(s_age=16).filter(s_name='小李')
# stus=Student.objects.filter(s_age=16,s_name='小李')
# exclude :不包含
# 查询姓名不等于小红的学生信息
# stus=Student.objects.exclude(s_name='小李')
# order_by :排序 +:升序 -:降序
#排序,安照id升序/降序===>asc/desc
# stus=Student.objects.all().order_by('id')
# stus = Student.objects.all().order_by('-id')
# values-->获取单个字段
# stus=Student.objects.all().values('id')
# return HttpResponse(stus)
# get(),first()-->获取单个对象
# stus=Student.objects.get(id=2)
# stus=Student.objects.filter(id=100).first()
# return HttpResponse(stus)
#first(),last()-->获取单个对象
# stus=Student.objects.all().order_by('id').last()
# stus = Student.objects.all().order_by('-id').first()
# stus = Student.objects.all().order_by('-id')[0]
# return HttpResponse(stus.id)
# 切片--->前面那个下标要考虑取值范围,后面那个不用
# stus = Student.objects.all().order_by('-id')[:100]
# 模糊查询
# select * from student name like '%李%'
# stus=Student.objects.filter(s_name__contains='哈')
# select * from student name like '小%'
# stus = Student.objects.filter(s_name__startswith='小')
# select * from student name like '%王'
# stus = Student.objects.filter(s_name__endswith='王')
#isnull/isnotnull判断是否为空
# stus = Student.objects.filter(s_name__isnull=False)
# stus = Student.objects.filter(s_name__isnotnull=False)
# in 判断在范围之内
# stus=Student.objects.filter(id__in=[1,2,6])
# 年龄大于16
# stus = Student.objects.filter(s_age__gt=16)
#pk
# stus = Student.objects.filter(id=3)
# stus=Student.objects.filter(pk=3)
# Q()将过滤条件组合,查询姓名叫小花的,或者年龄为18
# stus=Student.objects.filter(Q(s_name='小李') | Q(s_age=20))
# stus = Student.objects.filter(Q(s_name='小李') & Q(s_age=20))
# 查询姓名不叫小花的,或者年龄为18
# stus = Student.objects.filter(~Q(s_name='小李') | Q(s_age=20))
# F
# 查询语文成绩比数学成绩低10分的学生信息
stus=Student.objects.filter(math__gt=F('chinese')+10)
# 求平均值
stus_math=Student.objects.aggregate(Avg('math'))
print(stus_math)
# 获取学生姓名
# 方法一
# for stu in stus:
# print(stu.s_name)
# 方法二
stu_names=[stu.s_name for stu in stus]
print(stu_names)
return HttpResponse(stu_names)
def delete_stu(request):
#删除
stu=Student.objects.get(pk=1)
stu = Student.objects.filter(pk=1).first()
stu.delete()
return HttpResponse('删除')
def update_stu(request):
#更新
# 方法一
stu=Student.objects.get(pk=3)
stu.s_name='小哈'
stu.save()
# 方法二
# Student.objects.filter(id=2).update(s_name='哈哈')
return HttpResponse('修改')
def create_stu_info(request):
if request.method == 'GET':
data={
'11111141113':'锦江区',
'15214411111':'金柳渠',
'11311711131':'锦江区2',
'17611111133':'锦江区4'
}
for k,v in data.items():
StudentInfo.objects.create(phone=k,address=v)
return HttpResponse('添加信息')
def stu_add_stu_info(request):
if request.method == 'GET':
# 给id为1的学生添加拓展表中id为2的信息
stu = Student.objects.get(id=12)
# 绑定关系
# stu.stu_info_id=7
# 绑定关系2
stu.stu_info = StudentInfo.objects.get(id=13)
stu.save()
return HttpResponse('绑定关系')
def sel_phone_by_stu(request):
if request.method == 'GET':
# 方法一
stu=Student.objects.filter(id=3).first()
info_id=stu.stu_info_id
stu_info=StudentInfo.objects.get(pk=info_id)
phone=stu_info.phone
# 方法二:
stu=Student.objects.get(id=2)
stu_info=stu.stu_info
phone=stu_info.phone
print(phone)
return HttpResponse('寻找学生手机号')
def sel_stu_by_phone(request):
if request.method=='GET':
# 方法一
stu_info=StudentInfo.objects.get(phone='11111111131')
id=stu_info.id
stu1=Student.objects.get(stu_info_id=id)
# 方法二
stu_info=StudentInfo.objects.get(phone='11111111111')
# stu_info.student和stu_info.stu只能用一个,后者要设置 related_name='stu'
stu=stu_info.stud
s_name=stu.s_name
print(s_name)
return HttpResponse('通过手机号寻找学生')
def create_grade(request):
if request.method == 'GET':
# 创建班级
data_name=['c++','php','java']
for name in data_name:
Grade.objects.create(g_name=name)
return HttpResponse('添加班级')
def stu_add_grade(request):
if request.method== 'GET':
stu=Student.objects.get(id=8)
stu.g_id=Grade.objects.get(id=2)
stu.save()
return HttpResponse('给学生分配班级')
def sel_stu_by_grade(request):
if request.method=='GET':
grade=Grade.objects.get(g_name='java')
stu=grade.stud.all()
for name in stu:
print(name.s_name)
return HttpResponse('通过班级找学生')
def sel_grade_by_stu(request):
if request.method=='GET':
stu=Student.objects.get(s_name='李云龙')
grade=stu.g
return HttpResponse(grade.g_name)
def create_course(request):
if request.method=='GET':
# 添加课程
course_name=['数学','c语言','Java编程','英语']
for name in course_name:
Course.objects.create(c_name=name)
return HttpResponse('添加课程')
def create_stu_course(request):
if request.method=='GET':
# 学生2选择课程1
# stu=Student.objects.get(id=2)
#添加add()方法
# stu.c.add(3)
# 添加c语言和id等于3的学生关联关系
cou=Course.objects.get(c_name='Java编程')
# 添加add
cou.student_set.add(6)
#删除id=3的学生选的id=2的课程
# stu=Student.objects.get(id=2)
# stu.c.remove(2)
return HttpResponse('添加学生课程信息')
def sel_course_by_stu(request):
if request.method=='GET':
stu=Student.objects.get(id=3)
cous=stu.c.all()
for cou in cous:
print(cou.c_name)
return HttpResponse('查看某学生选课')
def sel_stu_by_course(request):
if request.method=='GET':
cou=Course.objects.get(c_name='英语')
stus=cou.student_set.all()
for stu in stus:
print(stu.s_name,cou.c_name)
return HttpResponse('查看选某课的学生')