Django models(day 7)

查询集:

在管理器上调用过滤器方法返下回查询集

查询集经过过滤器后返回的查询集

惰性执行:创建查询集不会带来任何数据的访问,直到调用数据时,才会访问数据

直接访问数据的情况:迭代、序列化、j与if语句合用


返回查询集的方法称为过滤器

返回符合条件的数据:

all()

>>> from myapp.models import Students,Grades
>>> Grades.objects.all()
, , , ]>


filter(key=values)

>>> Grades.objects.filter(pk=1)
]>


过滤掉符合条件的数据:exclude

order_by

values():一条数据就是一个对象(字典)

>>> Grades.objects.values()

), 'ggirlnum': 10, 'isDelete': False, 'gname': 'python01'}, {'gboynum': 18, 'id': 2, 'gdate': datetime.datetime(2018, 1, 7, 0, 0, tzinfo=), 'ggirlnum': 20, 'isDelete': False, 'gname': 'python02'}, {'gboynum': 13, 'id': 3, 'gdate': datetime.datetime(2018, 4, 5, 0, 0, tzinfo=), 'ggirlnum': 9, 'isDelete': False, 'gname': 'python03'}, {'gboynum': 16, 'id': 4, 'gdate': datetime.datetime(2018, 5, 4, 0, 0, tzinfo=), 'ggirlnum': 11, 'isDelete': False, 'gname': 'python04'}]>

 

>>>Grades.objects.get()

count()  返回查询对象的个数

>>> Grades.objects.count()
4

first()

>>> Grades.objects.first()



last()

>>> Grades.objects.last()



exists()

>>> Grades.objects.exists()

True


判断查询集中是否有数据

>>> Grades.objects.count()
4

>>> Grades.objects.exists()
True


二、限制查询集

# 显示前五条学生
def stu2 (request):
    stulist=Students.stu_objects.all()[0:5]
    return render(request,'myapp/students.html',
                  {"students":stulist})
url(r'^stu2/$',views.stu2),

Django models(day 7)_第1张图片




# 分页显示


# 0-5 5-10 10-15
# 1     2   3
def stupage(request, page):
    page=int(page)
    stulist=Students.stu_objects.all()[(page-1)*5:page*5]
    return render(request,'myapp/students.html',
                  {"students":stulist})


url('^stu/(\d+)$',views.stupage)

查询集的缓冲,在新建的查询集中,缓冲首次为空,第一次对查询集球值,会发生数据缓冲

字段查询:属性名称_比较运算符=值                                        转义:

外键查询:属性名_id

比较运算符:exact判断 contains是否包含

def stusearch(request):
    # stulist=Students.stu_objects.filter(sname__contains='bob')
    # stulist=Students.stu_objects.filter(sname__startswith='b')
    # stulist = Students.stu_objects.filter(sname__endswith='b')
    # stulist = Students.stu_objects.filter(pk__in=[2,4,6,8])
    # stulist = Students.stu_objects.filter(sage__gt=30)
    # stulist = Students.stu_objects.filter(sage__lte=15)
    stulist = Students.stu_objects.filter(lasttime__year=2018)

def stusearch(request):
    stulist=Students.stu_objects.filter(sname__contains='bob')
    return render(request,'myapp/students.html',
                  {"students":stulist})

Django models(day 7)_第2张图片



聚合函数:

使用 asggregate()  函数返回聚合函数的值:Avo   MIN Sum Count  Max

from django.db.models import Max,Min
def stusearch(request):
    # stulist=Students.stu_objects.filter(sname__contains='bob')
    # stulist=Students.stu_objects.filter(sname__startswith='b')
    # stulist = Students.stu_objects.filter(sname__endswith='b')
    # stulist = Students.stu_objects.filter(pk__in=[2,4,6,8])
    # stulist = Students.stu_objects.filter(sage__gt=30)
    # stulist = Students.stu_objects.filter(sage__lte=15)
    # stulist = Students.stu_objects.filter(lasttime__year=2018)
    stulist=Students.stu_objects.filter(sname__contains='J')
    maxage=Students.stu_objects.aggregate(Max('sage'))
    print(maxage)


    return render(request,'myapp/students.html',
                  {"students":stulist})

{'sage__max': 50}


F对象:比较同一个对象下不同的属性:例如找出girlnum>boynum的班级

# F对象:比较同一个对象下不同的属性:例如找出girlnum>boynum的班级
from django.db.models import F,Q
def grades_comparison(request):
    g=Grades.objects.filter(ggirlnum__gt=F('gboynum'))
    print(g)
    return HttpResponse("yes")

# 或的关系
# stulist = Students.stu_objects.filter(Q(pk__lt=15)|Q(sage__lt=25))
stulist = Students.stu_objects.filter(~Q(pk__lt=15))

关联查询:带有bob学生描述的学生数据是属于哪个班级的:对象名小写__属性__


# 关联查询:带有bob学生描述的数据是属于哪个班级的:对象名小写__属性

grade=Grades.objects.filter(Students__scontend__contains="bob")
print(grade)




from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
def index(request):
    return HttpResponse("I love China")
from django.shortcuts import render
from . models import Grades
# Create your views here.
from django.http import HttpResponse
def index(request):
    return  HttpResponse("I love China")
def grades(request):
    # models里取数据
    gradeslist=Grades.objects.all()
    # 将数据传输给模板模板在渲染页面,再将渲染好的页面返回浏览器
    return render(request,'myapp/grades.html',
                  {"grades":gradeslist})
from .models import Students
def stu (request):
    stulist=Students.stu_objects.all()
    return render(request,'myapp/students.html',
                  {"students":stulist})


# 显示前五条学生
def stu2 (request):
    stulist=Students.stu_objects.all()[0:5]
    return render(request,'myapp/students.html',
                  {"students":stulist})
# 分页显示


# 0-5 5-10 10-15
# 1     2   3
def stupage(request, page):
    page=int(page)
    stulist=Students.stu_objects.all()[(page-1)*5:page*5]
    return render(request,'myapp/students.html',
                  {"students":stulist})
from django.db.models import Max,Min
def stusearch(request):
    # stulist=Students.stu_objects.filter(sname__contains='bob')
    # stulist=Students.stu_objects.filter(sname__startswith='b')
    # stulist = Students.stu_objects.filter(sname__endswith='b')
    # stulist = Students.stu_objects.filter(pk__in=[2,4,6,8])
    # stulist = Students.stu_objects.filter(sage__gt=30)
    # stulist = Students.stu_objects.filter(sage__lte=15)
    # stulist = Students.stu_objects.filter(lasttime__year=2018)
    # stulist=Students.stu_objects.filter(sname__contains='J')
    # 或的关系
    # stulist = Students.stu_objects.filter(Q(pk__lt=15)|Q(sage__lt=25))
    stulist = Students.stu_objects.filter(~Q(pk__lt=15))
    maxage=Students.stu_objects.aggregate(Max('sage'))
    print(maxage)

    # 关联查询:带有bob学生描述的数据是属于哪个班级的:对象名小写__属性

    grade=Grades.objects.filter(Students__scontend__contains="bob")
    print(grade)

    return render(request,'myapp/students.html',
                  {"students":stulist})



# F对象:比较同一个对象下不同的属性:例如找出girlnum>boynum的班级,支持算数运算
from django.db.models import F,Q
def grades_comparison(request):
    g=Grades.objects.filter(ggirlnum__gt=F('gboynum')+20)
    print(g)
    return HttpResponse("yes")




def addstudent(request):
    grade=Grades.objects.get(pk=2)
    stu=Students.createStudent("li",25,True,"I am li",grade,"2018-5-1", "2017-5-2")
    stu.save()
    return HttpResponse("Hello")

def addstudent2(request):
    grade=Grades.objects.get(pk=1)
    stu=Students.stu_objects.createStudent2("bob",25,True,"I am bob",grade,"2018-5-1", "2017-5-2")
    stu.save()
    # stu=Students.stu_objects.createStudent2()
    return HttpResponse("hello")



from django.db import models

# Create your models here.

# -*- coding: utf-8 -*-

class Grades(models.Model):
    gname=models.CharField(max_length=20)
    gdate=models.DateTimeField()
    ggirlnum=models.IntegerField()
    gboynum=models.IntegerField()
    isDelete=models.BooleanField(default=False)

    def __str__(self):
        return self.gname

    class Meta:
        db_table="grades"
        ordering=['id']


class StudentsManager(models.Manager):
    def get_queryset(self):
        return super(StudentsManager,self).get_queryset().filter(isDelete=False)

    def createStudent2(self, name, age, gender, contend, grade, lastT, createT, isD=False):
    # def createStudent2(self):

        stu=self.model()
        print(type(stu))

        stu.sname=name

        stu.sage=age
        stu.sgender = gender
        stu.scontend=contend
        stu.sgrade=grade
        stu.lasttime=lastT
        stu.createtime=createT
        return stu
class Students(models.Model):


    #自定义管理器
    stu_objects=StudentsManager()

    stu_object=models.Manager()
    sname=models.CharField(max_length=20)
    sgender=models.BooleanField(default=True)
    sage=models.IntegerField(db_column="age")
    scontend=models.CharField(max_length=20)
    isDelete=models.BooleanField(default=False)
    # 关联外键
    # -对多(外键在多的地方关联)
    sgrade=models.ForeignKey("Grades")
    # 说明:1.不需要定义主键,自动生成,且自动增加gra
    def __str__(self):
        return self.sname
    lasttime=models.DateTimeField(auto_now=True)
    createtime=models.DateTimeField(auto_now_add=True)
    class Meta:
        db_table="students"
        ordering=['id']


    @classmethod
    def createStudent(cls,name,age,gender,contend,grade,lastT,createT,isD=False):
        stu=cls(sname=name,sage=age,sgender=gender,scontend=contend,\
                lasttime=lastT,sgrade=grade,createtime=createT,isDelete=isD)
        return stu

from django.conf.urls import url,include
from.import views
urlpatterns=[
    url(r'^$',views.index),
    url(r'^students/$',views.stu),
    url(r'^addstudent/$',views.addstudent),
    url(r'^addstudent2/$',views.addstudent2),
    url(r'^stu2/$',views.stu2),
    url('^stu/(\d+)$',views.stupage),
    url('^stusearch$',views.stusearch),
    url('^gra$',views.grades_comparison)

]
html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生信息title>
head>
<body>
    <h1>学生信息列表h1>
    <ul>
        {% for student in students %}
        <li>
            {{ student.sname }}--{{ student.scontend }}
        li>
        {% endfor %}
    ul>


body>
html>

你可能感兴趣的:(Django models(day 7))