from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,Context
from blog.models import Person
# Create your views here.
def student_list(request):
t = loader.get_template('student_list.html')
#studentList = Person.objects.all().order_by('age') #过滤
studentList = Person.objects.all().filter(age__gt = 18) #tiaojian > 18 (age = 18) = 18 (age__gte = 18) >= 18
c = Context({ 'studentList':studentList })
return HttpResponse(t.render(c))
常用查询函数:
get() 获取单个符合条件的, 没有获取到返回空 获取到多个报错
all() 获取所有符合条件的
filter() 等于 ,filter(a = ‘222’) 筛选出a = ‘222’ filter(name__in = [‘xiaoming’,’xiaohong’])
exclide() 于filter相反
order_by() 排序 , 对上面筛选到的结果进行排序order_by(‘-age’) 逆向排序
distinct().values(‘field_name’) 去点掉重复的
[n:m] 起始与偏移量,[0:10] 取出1~10
常用查询方法:
修改数据库值:
修改 id = 1 的信息
from django.http import HttpResponse
from django.template import loader,Context
from blog.models import Person
# Create your views here.
def student_list(request):
t = loader.get_template('student.html')
newrow = Person(name = 'LiMing',age = 18,initime = '2016-02-02')
newrow.save() # 等同于 insert 插入一行
student = Person.objects.get(id = 2)
student.delete() #删除 id = 2 的
#Person.objects.all().delete() #删除所有
studentList = Person.objects. filter(age_lt = 30).update(name = 'xyz') #把年龄小于30 岁的人的name改为 xyz
student = Person.objects.get(id = 1) #获得的是单个数据 不是数组
student.name = 'Tom'
student.age = '29'
student.save() #保存
c = Context({ 'student':student })
return HttpResponse(t.render(c))
--------------------------------------------------------------------------
studentList = Person.objects. filter(age_lt = 30).update(name = 'xyz') 相当于:
update Person set name = 'xyz' where age < 30