模型层单表操作
单表操作
例:
1. 单表的查询
1. 单表查询所有用户:models.Book.objects.all()
得到的是 queryset对象(当成列表),列表里面,一个一个的对象[user1,user2]
2. render(request, 'booklist.html', {'book_list': ret})
3. 模板里: {% for user in book_list %}
#要循环的内容
{{book.name}}
{% endfor%}
4. get请求携带参数:
http://127.0.0.1:8000/deleteuser/?id=1
后台取值:request.GET.get('id')
request.GET['id']
5. 前台post提交的数据取值:name=request.POST.get('name')
查询的API
all(): 查询所有结果
filter(**kwargs): 它包含了与所给筛选条件相匹配的对象
get(**kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象 超过一个或者没有都会抛出错误。
exclude(**kwargs): 它包含了与所给筛选条件不匹配的对象
order_by(*field): 对查询结果排序('-id')
reverse(): 对查询结果反向排序
count(): 返回数据库中匹配查询(QuerySet)的对象数量。
first(): 返回第一条记录
last(): 返回最后一条记录
exists(): 如果QuerySet包含数据,就返回True,否则返回False
values(*field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列
model的实例化对象,而是一个可迭代的字典序列
values_list(*field): 它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
distinct(): 从返回结果中剔除重复纪录
基于双下划线的模糊查询
Book.objects.filter(price__in=[100,200,300])
Book.objects.filter(price__gt=100)
Book.objects.filter(price__lt=100)
Book.objects.filter(price__gte=100)
Book.objects.filter(price__lte=100)
Book.objects.filter(price__range=[100,200])
Book.objects.filter(title__contains="python")
Book.objects.filter(title__icontains="python")
Book.objects.filter(title__startswith="py")
Book.objects.filter(pub_date__year=2012)
2. 单表的删除
关键字: delete()
models.Book.objects.filter(id=id).delete()
3. 单表的增加
两种方式:
1 book_obj=Book.objects.create(title="python葵花宝典",state=True,price=100,publish="苹果出版社",pub_date="2012-12-12")
2 book_obj=Book(title="python葵花宝典",state=True,price=100,publish="苹果出版社",pub_date="2012-12-12")
book_obj.save()
4. 单表的修改
关键字: update()
Book.objects.filter(title__startswith="py").update(price=120)
前后端交互
<form action="/updateuser/?id={{ book.id }}" method="post">
<p><input type="hidden" name="id" value="{{ book.id }}"></p>
<p>书名: <input type="text" name="name" value="{{ book.name }}"></p>
<p>价格: <input type="text" name="price" value="{{ book.price }}"></p>
<p>出版社: <input type="text" name="publish" value="{{ book.publish }}"></p>
<input type="submit" value="提交">
</form>