django内置序列化组件(drf前身)
"""前后端分离的项目,视图函数只需要返回json格式的数据即可"""
from app01 import models
from django.http import JsonResponse
def ab_ser_func(request):
# 1.查询所有的书籍对象
book_queryset = models.Book.objects.all() # queryset [对象、对象]
# 2.封装成大字典返回
data_dict = {}
for book_obj in book_queryset:
temp_dict = {}
temp_dict['pk'] = book_obj.pk
temp_dict['title'] = book_obj.title
temp_dict['price'] = book_obj.price
temp_dict['info'] = book_obj.info
data_dict[book_obj.pk] = temp_dict # {1:{},2:{},3:{},4:{}}
return JsonResponse(data_dict)
序列化组件(django自带 后续学更厉害的drf)
# 导入内置序列化模块
from django.core import serializers
# 调用该模块下的方法,第一个参数是你想以什么样的方式序列化你的数据
res = serializers.serialize('json', book_queryset)
return HttpResponse(res)
批量操作数据
def ab_bk_func(request):
# 1.往books表中插入10万条数据
# for i in range(1,100000);
# models.Books.objects.create(title='第%s本书'% i)
"""直接循环插入,10s 500条左右"""
book_obj_list = []
for i in range(1,100000):
book_obj = models.Books01(title='第%本书' % i) # 循环创建书籍对象,没有操作ORM
book_obj_list.append(book_obj)
# 批量插入数据
models.Books01.objects.bulk_create(book_obj_list)
"""使用ORM提供的批量插入操作 5s 10万条左右"""
# 查询出所有的表中并展示到前端页面
book_querset = models.Book01.objects.all()
return render(request,'Bkpage.html',locals())
分页器思路
推导流程:
1.queryset支持切片操作(正数)
2.研究各个参数之间的数学关系
每页固定展示多少条数据、起始位置、终止位置
3.自定义页码参数
current_page = request.GET.get('page')
4.前端展示分页器样式
5.总页码数问题
divmod内置函数,括号内放两个数字,结果是商和余数
6.前端页面页码个数渲染问题
后端产生 前端渲染
自定义分页器
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
"""
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
if current_page < 1:
current_page = 1
self.current_page = current_page
self.all_count = all_count
self.per_page_num = per_page_num
# 总页码
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager
self.pager_count = pager_count
self.pager_count_half = int((pager_count - 1) / 2)
@property
def start(self):
return (self.current_page - 1) * self.per_page_num
@property
def end(self):
return self.current_page * self.per_page_num
def page_html(self):
# 如果总页码 < 11个:
if self.all_pager <= self.pager_count:
pager_start = 1
pager_end = self.all_pager + 1
# 总页码 > 11
else:
# 当前页如果<=页面上最多显示11/2个页码
if self.current_page <= self.pager_count_half:
pager_start = 1
pager_end = self.pager_count + 1
# 当前页大于5
else:
# 页码翻到最后
if (self.current_page + self.pager_count_half) > self.all_pager:
pager_end = self.all_pager + 1
pager_start = self.all_pager - self.pager_count + 1
else:
pager_start = self.current_page - self.pager_count_half
pager_end = self.current_page + self.pager_count_half + 1
page_html_list = []
# 添加前面的nav和ul标签
page_html_list.append('''
<nav aria-label='Page navigation>'
<ul class='pagination'>
''')
first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
page_html_list.append(first_page)
if self.current_page <= 1:
prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
else:
prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
page_html_list.append(prev_page)
for i in range(pager_start, pager_end):
if i == self.current_page:
temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
else:
temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
page_html_list.append(temp)
if self.current_page >= self.all_pager:
next_page = '<li class="disabled"><a href="#">下一页</a></li>'
else:
next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
page_html_list.append(next_page)
last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
page_html_list.append(last_page)
# 尾部添加标签
page_html_list.append('''
</nav>
</ul>
''')
return ''.join(page_html_list)
自定义分页器的使用
后端写法;
def ab_pg_func(request):
book_queryset = models.Books01.objects.all()
from app01.utils.mypage import Pagination # 导入自定义分页器类
current_page = request.GET.get('page') # 获取前端的get请求是第几页
page_obj = Pagination(current_page=current_page, all_count=book_queryset.count())
"产生一个分页对象,传参,当前页,数据的总数"
page_queryset = book_queryset[page_obj.start:page_obj.end]
"对全部的数据对象进行切割"
return render(request, 'pgPage.html', locals())
前端写法:
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
{% for book in page_queryset %}
<p>{{ book.title }}</p>
{% endfor %}
{{ page_obj.page_html|safe }}
</div>
</div>
</div>
form组件
小需求:获取用户数据并发送给后端校验,后端返回不符合校验规则的提示信心
传统写法:
def ajax_func(request):
if request.method == 'POST':
name = request.POST.get('name')
pwd = request.POST.get('pwd')
user_dict = {'username': '', 'password': ''}
if name == 'jason':
user_dict['username'] = '账号不能是jason'
if pwd == '123':
user_dict['password'] = '密码不能是123'
return render(request, 'ajax_func.html', locals())
return render(request, 'ajax_func.html')
form组件功能
1.自动校验数据
class MyForm(forms.Form): # 需要先定义好我们的要求
username = forms.CharField(min_length=3, max_length=8)
"规定字符串的最长是8,最短是3"
age = forms.IntegerField(min_value=0, max_value=100)
"规定年龄的位正整数,最小是0,最大是100"
email = forms.EmailField()
"规定email必须是邮箱的格式"
def ajax_func(request):
if request.method == 'POST':
name = request.POST.get('name') # 获取前端数据
age = request.POST.get('age')
email = request.POST.get('email')
form_obj = MyForm({'username': name, 'age': age, 'email': email}) # 产生对象
form_obj.is_valid() # 必须先判断拿到的数据是不是符合要求的
# form_date =
print(form_obj.cleaned_data) # 拿符合数据的要求
form_err = form_obj.errors # 不符合数据的要求
return render(request, 'ajax_func.html', locals())
return render(request, 'ajax_func.html')
1.只会校验类中定义好的字段对应的数据,多穿的根本不做任何操作
2.默认情况下类中定义好的字段都是必填的
2.自动生成标签
3.自动展示信息
标签:self,request,django,current,book,组件,pager,page From: https://www.cnblogs.com/zhanghong1229/p/16994916.html