【Django总结】Views.py

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

from django.db import connection
from django.db.models.query import QuerySet


def getSql(res):
    if type(res) == QuerySet:
        sql = str(res.query)
    else:
        queries = connection.queries
        sql = str(queries[-1].get('sql'), 'utf-8')
    print('\033[1;34m' + '=' * len(sql))
    print(sql)
    print('=' * len(sql) + '\033[0m')


def index(request):
    return HttpResponse("Hello,world. You're at the polls index.")


def mydate(request, year, month, day):
    return HttpResponse(str(year) + '/' + str(month) + '/' + str(day))


def mydate_re(request, year, month, day):
    return HttpResponse('re'+ str(year) + '/' + str(month) + '/' + str(day))


def student_add(request):
    # save方式一
    stu_obj = students()
    # stu_obj.id = 5
    stu_obj.stu_name = 'zcj'
    stu_obj.stu_sex = ''
    stu_obj.stu_age = 18
    stu_obj.save()
    # save方式二
    stu_obj = students(stu_name='dzx', stu_age=2, stu_sex='')
    stu_obj.save()
    # create方式一
    students.objects.create(stu_name='dyx', stu_age=1, stu_sex='')
    # create方式二 推荐
    students.objects.create(**{'stu_name': 'dxx', 'stu_age': 30, 'stu_sex': ''})
    return HttpResponse('Add student {} success'.format('zcj,dzx,dyx,dxx'))


def student_delete(request, id):
    stu_obj = students.objects.filter(id=id)
    stu_obj.delete()
    return HttpResponse('Delete id:{} data success'.format(id))


def students_search(request, id):
    if id != 'all':
        stu_values = students.objects.filter(id=id).values()
    else:
        stu_values = students.objects.values()
    return HttpResponse('Search students data:{}'.format(stu_values[0]))


def students_aggregation(request, opr):
    if opr.upper() == 'F':
        stu_obj = students.objects.filter(stu_age__gt=F('stu_age') - 1).values()[0]
    elif opr.upper() == 'Q':
        stu_obj = students.objects.filter(Q(stu_age__gt=1) & Q(stu_age__lt=18)).values()[0]
    elif opr.upper() == 'AVG':
        stu_obj = students.objects.aggregate(Avg('stu_age')).get('stu_age__avg')
    elif opr.upper() == 'MAX':
        stu_obj = students.objects.aggregate(Max('stu_age')).get('stu_age__max')
    elif opr.upper() == 'MIN':
        stu_obj = students.objects.aggregate(Min('stu_age')).get('stu_age__min')
    elif opr.upper() == 'COUNT':
        stu_obj = students.objects.aggregate(Count('stu_age')).get('stu_age__count')
    elif opr.upper() == 'ANNOTATE':
        stu_obj = students.objects.values('stu_name').annotate(avg=Avg('stu_age')).values('stu_name', 'avg')
        print(stu_obj[0])
    else:
        stu_obj = students.objects.all()
        getSql(stu_obj)
    return HttpResponse('students aggregation return:{}'.format(stu_obj[0]))
View Code

 

posted @ 2020-06-26 15:47  gtea  阅读(155)  评论(0编辑  收藏  举报