day03 简单的数据增删改查操作和简单的路由跳转和多对多

app/views.py

from django.db.models import Avg, Sum, Count, Max, Min, F, Q
from django.http import HttpResponse
from django.shortcuts import render

from app.models import Student, StudentInfo, Grade, Course


def hello(request):
    return HttpResponse('hello world')


def add_stu(request):
    if request.method == 'GET':
        # 第一种方式: 新增学生信息
        # stu = Student()
        # stu.s_name = '小明'
        # stu.age = 29
        # stu.save()
        # 第二种方式: create()
        # objects: 管理器
        for i in range(10):
            Student.objects.create(s_name='小花' + str(i), age=20 + i)

        # flask中使用flask-sqlalchemy,Student.query
        # tornado中使用sqlalchemy,session.query(Student).filter
        # Django中使用自带的ORM,Student.objects

        return HttpResponse('创建成功')


def del_stu(request):
    if request.method == 'GET':
        # 实现删除功能
        # filter(字段=值)
        # 删除单条数据
        stu = Student.objects.filter(s_name='小明').first()
        stu.delete()
        # 删除多条数据
        Student.objects.filter(s_name='小花').delete()
        return HttpResponse('删除成功')


def update_stu(request):
    if request.method == 'GET':
        # 第一种方式: 修改数据, save()
        # stu = Student.objects.filter(s_name='小花').first()
        # stu.age = 19
        # stu.save()
        # 第二种方式: update()
        Student.objects.filter(s_name='小花').update(age=18, s_name='小强')

        return HttpResponse('修改数据')


def sel_stu(request):
    if request.method == 'GET':
        # 查询数据
        stu = Student.objects.filter(s_name='小明').all()
        # stu的结果类型为QuerySet,取其中的数据,first(),last(),[下标]

        # flask: get(主键值) ,查询结果为获取主键所在行的对象
        # django: get(任何条件),查询满足条件的结果即可
        stu = Student.objects.get(s_name='小明')
        print(stu)
        stu = Student.objects.filter(s_name='小明').first()
        print(stu)
        # django: get(条件),查询条件必须查找到结果,
        # 如果查询不到结果则报错‘DoesNotExist’
        # stu = Student.objects.get(id=1000)
        # 如果查询结果超过一个对象,则报错‘MultipleObjectsReturned ’
        # stu = Student.objects.get(age=23)

        # 总结: get(): 查询条件必须成立且结果只能有一个
        print(stu)

        # filter()过滤满足条件, exclude()过滤不满足条件
        stus = Student.objects.exclude(age=23).all()
        print(stus)

        # count()统计多少条数据
        stus = Student.objects.all()
        print(len(stus))
        stus = Student.objects.all().count()
        print(stus)

        # 排序, 升序order_by('id')  降序order_by('-id')
        stus = Student.objects.all().order_by('-id')
        stus = Student.objects.all().order_by('id')
        print(stus)

        # values(): 序列化,将对象的属性转化为字典格式数据
        stus = Student.objects.all().values('s_name', 'age')
        print(stus)

        # contains,字段__contains = ’值‘
        stus = Student.objects.filter(s_name__contains='花').all()
        stus = Student.objects.filter(s_name__startswith='花').all()
        print(stus)
        stus = Student.objects.filter(s_name__endswith='9').all()
        print(stus)

        # in,  pk=id
        stus = Student.objects.filter(id__in=[1, 2, 3, 4, 5, 6, 7]).all()
        stus = Student.objects.filter(pk__in=[1, 2, 3, 4, 5, 6, 7]).all()
        print(stus)

        # 大于23,gt,gte,lt,lte
        stus = Student.objects.filter(age__gt=23).all()
        stus = Student.objects.filter(age__gte=23).all()
        print(stus)

        # 聚合,Count(), Max(), Min()
        # select s_name, max(chengji) from student;
        # from django.db.models import Avg
        stus = Student.objects.all().aggregate(Avg('age'))
        print(stus)

        # 查询语文成绩大于数据成绩的学生信息
        # sql: select * from student where yuwen > math;
        stus = Student.objects.filter(yuwen__gt=F('math'))
        stus = Student.objects.filter(yuwen__gt=F('math') + 10)
        print(stus)

        # Q,且,或,非
        stus = Student.objects.filter(s_name__contains='花', age=23).all()
        # 或者条件
        stus = Student.objects.filter(Q(s_name__contains='花') | Q(age=23)).all()
        # ~非
        stus = Student.objects.filter(~Q(s_name__contains='花')).all()
        stus = Student.objects.exclude(s_name__contains='花').all()
        print(stus)

        return HttpResponse('查询数据成功')


def add_stu_info(request):
    if request.method == 'GET':
        # 向拓展表中添加信息
        stu_info = StudentInfo()
        stu_info.phone = '13551370671'
        stu_info.save()
        # 拓展表主键id值
        s_id = stu_info.id
        stu= Student.objects.filter(s_name='小明').first()
        # 第一种写法: 学生对象.OneToOneFiled字段 = 关联对象
        stu.stuinfo = stu_info
        # 第二种写法: 学生对象.OneToOneFiled字段_id = 关联对象.id
        stu.stuinfo_id = stu_info.id
        stu.save()
        return HttpResponse('添加拓展表信息')


def sel_stuinfo_by_stu(request):
    if request.method == 'GET':
        # 通过学生信息找拓展表信息
        stu = Student.objects.get(s_name='小明')
        # StudentInfo.objects.get(pk=stu.stuinfo_id)
        # 学生对象.OneToOneFiled字段
        stu.stuinfo
        return HttpResponse('获取拓展表信息成功')


def sel_stu_by_info(request):
    if request.method == 'GET':
        # 通过拓展表中的手机号码13551370673找学生信息
        stuinfo = StudentInfo.objects.filter(phone='13551370673').first()
        # stu = Student.objects.filter(stuinfo=stuinfo)
        # stu = Student.objects.filter(stuinfo_id=stuinfo.id)
        # print(stu)
        # 拓展表对象.关联的模型名称小写
        stu = stuinfo.student
        # 定义related_name参数,拓展表对象.related_name值
        stu = stuinfo.stu
        print(stu)
        return HttpResponse('通过拓展表信息查询学生表信息')


def add_grade(request):
    if request.method == 'GET':
        # 添加班级信息,并给学生分配班级
        names = ['Python班级', 'Java班级', 'Php班级', 'C++班级']
        for name in names:
            if not Grade.objects.filter(g_name=name).exists():
                Grade.objects.create(g_name=name)
        # 分配班级
        stus = Student.objects.filter(pk__in=[1, 2, 3, 4, 5, 6]).all()
        g = Grade.objects.filter(g_name='Python班级').first()
        for stu in stus:
            stu.grade = g
            # stu.grade_id = g.id
            stu.save()
        return HttpResponse('添加班级和学生信息')


def sel_grade_by_stu(request):
    if request.method == 'GET':
        # 通过学生查询班级信息
        stu = Student.objects.filter(s_name='小明').first()
        g = stu.grade
        print(g)
        # 班级查询学生
        stus = g.student_set.all()
        stus = g.stu.all()

        return HttpResponse('通过学生查询班级成功')


def add_course(request):
    if request.method == 'GET':
        # 添加课程信息
        names = ['大学语文', '日语', '数电', '模电', '物理', '线代']
        for name in names:
            cou = Course()
            cou.c_name = name
            cou.save()
        return HttpResponse('创建课程成功')


def sel_cou_by_stu(request):
    if request.method == 'GET':
        # 查询id为1的学生所选择的课程信息
        stu = Student.objects.get(pk=1)
        # 学生查询课程
        stu.course

        # 课程查询学生
        cou = Course.objects.get(pk=1)
        cou.student_set.all()
        cou.stu.all()
        return HttpResponse('多对多的查询成功')


def add_del_stu_cou(request):
    if request.method == 'GET':
        # 增删中间表信息
        # 给小明分配‘日语’,‘数电’,‘模电’
        stu = Student.objects.filter(s_name='小明').first()
        cou1 = Course.objects.get(c_name='日语')
        cou2 = Course.objects.get(c_name='数电')
        cou3 = Course.objects.get(c_name='模电')
        # 新增中间表数据
        # stu.course.add(cou1)
        # stu.course.add(cou2)
        # stu.course.add(cou3)
        # cou1.stu.add(学生对象)

        # 删除中间表数据
        stu.course.remove(cou2)
        stu.course.remove(cou3)

        return HttpResponse('操作中间表信息成功')


def on_delete_stu(request):
    if request.method == 'GET':
        # 演示删除,on_delete参数的效果
        stuinfo = StudentInfo.objects.get(id=1)
        stuinfo.delete()
        # models.CASCADE 表示:主键所在行的数据被删,外键所在行的数据也会被删
        # models.PROTECT 表示: 主键有对应的外键数据时,不让删除主键的数据
        # models.SET_NULL 表示: 主键删除,外键置空

        return HttpResponse('on_delete演示成功')


def index(request):
    if request.method == 'GET':
        # TODO: render(request)中的request后面讲
        stus = Student.objects.all()
        content_h2 = '

hello world

' return render(request, 'index.html', {'students': stus, 'content_h2': content_h2}) def params(request, id): if request.method == 'GET': return HttpResponse('id:%s' % id) def str_params(request, name): if request.method == 'GET': return HttpResponse('name:%s' % name) def uid_params(request, uid): if request.method == 'GET': # uuid.uuid4() return HttpResponse('uid:%s' % uid) def path_params(request, ph): if request.method == 'GET': return HttpResponse('path:%s' % ph) def year_parmas(request, day, year, month): if request.method == 'GET': return HttpResponse('%s年%s月%s日' % (year, month, day))

app/urls.py

from django.urls import path, re_path

from app.views import *


urlpatterns = [
    path('hello/', hello),
    path('add_stu/', add_stu),
    path('del_stu/', del_stu),
    path('update_stu/', update_stu),
    path('sel_stu/', sel_stu),
    path('add_stu_info/', add_stu_info),
    path('sel_stuinfo_by_stu/', sel_stuinfo_by_stu),
    path('sel_stu_by_info/', sel_stu_by_info),
    path('add_grade/', add_grade),
    path('sel_grade_by_stu/', sel_grade_by_stu),
    path('add_course/', add_course),
    path('sel_cou_by_stu/', sel_cou_by_stu),
    path('add_del_stu_cou/', add_del_stu_cou),
    path('on_delete_stu/', on_delete_stu),
    path('index/', index),
    # 接收传参数的路由url
    path('params//', params),
    path('str_params//', str_params),
    path('uuid_params//', uid_params),
    path('path_params//', path_params),
    # re_path 替代2.0一下版本中的url
    re_path('year_params/(\d+)/(\d+)/(\d+)/', year_parmas),
    # ?P\d+
    re_path('p_params/(?P\d+)/(?P\d+)/(?P\d+)/', year_parmas),
]

app/models.py

from django.db import models


class Article(models.Model):
    # 模型中可不用定义自增的id主键,迁移时会自动创建
    # 指定title字段,长度为10,且不能为空
    title = models.CharField(max_length=10, null=False)
    desc = models.CharField(max_length=100, null=True)

    class Meta:
        # 指定表明
        db_table = 'article'


class StudentInfo(models.Model):
    address = models.CharField(max_length=50, null=True)
    phone = models.CharField(max_length=11, null=True)

    class Meta:
        db_table = 'stu_info'


class Grade(models.Model):
    g_name = models.CharField(max_length=10, unique=True, null=False)

    class Meta:
        db_table='grade'


class Course(models.Model):
    c_name = models.CharField(max_length=10, unique=True, null=False)

    class Meta:
        db_table = 'course'


class Student(models.Model):
    # 长度为10,且唯一不能为空的姓名s_name字段
    s_name = models.CharField(max_length=10, unique=True, null=False)
    age = models.IntegerField(default=18)
    # auto_now_add: 表示第一次创建数据时,自动默认为当前创建的时间
    create_time = models.DateTimeField(auto_now_add=True)
    # auto_now: 表示修改时,自动更新为修改的时间
    operate_time = models.DateTimeField(auto_now=True)
    is_delete = models.BooleanField(default=0)
    # 定义浮点数总长度3为,小数点后1位
    yuwen = models.DecimalField(max_digits=3, decimal_places=1, null=True)
    math = models.DecimalField(max_digits=3, decimal_places=1, null=True)
    # 一对一: 定义在关联的两个模型中的任何一方都可以
    stuinfo = models.OneToOneField(StudentInfo, related_name='stu', on_delete=models.SET_NULL, null=True)
    # 一对多: 定义在’多‘的一方
    grade = models.ForeignKey(Grade, related_name='stu', on_delete=models.CASCADE, null=True)
    # 多对多
    course = models.ManyToManyField(Course, related_name='stu')
    # TimeFiled
    # DateField
    # ImageField
    # TextField
    # DecimalField: 5位数,小数点占两位, 999.99
    # AutoField
    # FloatField


    class Meta:
        db_table = 'student'


你可能感兴趣的:(day03 简单的数据增删改查操作和简单的路由跳转和多对多)