在sqliteStudio中为student表增加几条记录
...
url(r'^student_list/$', 'blog.views.student_list')
t = loader.get_template('student_list.html')
studentList = Student.objects.all()
c = Context({"studentList": studentList})
return HttpResponse(t.render(c))
在blog/urls中增加
urlpatterns = [
]
-----------------
在blog/views里增加视图函数
...
from blog.models import Student #注意是 blog.models
...
def student_list(request):
----------------
增加student_html模板
{% for student in studentList%}
html...
{%endfor%}
----------------------
manage.py runserver
http:///.../blog/student_list/
-------------------------------
修改视图函数
排序
studentList = Student.objects.all().order_by('age') 按年龄升序
studentList = Student.objects.all().order_by('-age') 按年龄降序
studentList = Student.objects.order_by('age') 按年龄升序
studentList = Student.objects.order_by('-age') 按年龄降序
多字段排序
studentList = Student.objects.order_by('age','id') 按年龄升序
过滤
studentList = Student.objects.filter(age=18)
studentList = Student.objects.filter(age__gt = 18) 年龄大于18的
studentList = Student.objects.filter(name__contains = "赵")
更多的
__exact
等于
__iexact
忽略大小写的等于
__contains
__icontains
__gt
__gte
__lt
__lte
__in
在list中
__startswith
__istartswith
__endswith
__iendswith
__range 在...范围内
__year 日期字段的年份
__month
__day
__isnull = True/False
--------------------------------
获得单个对象
student = Student.objects.get(id = 1)
--------------------------------
修
改数据库记录
student.name = 'kylie'
student.age=30
student.save()
批量更
改
studentList = Student.objects.filter(age__lt = 30).update(name = name +"*")
新
增记录
newStu = Student(name = 'coco', age = 41, sex= 0)
newStu.save()
删除记录
student.delete()
批量删除
Student.objects.all().delete()