python与mysql运用示例

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


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('通过学生查询班级成功')

你可能感兴趣的:(python与mysql运用示例)