目录
一、django内置序列化组件
1.前夕
前后端分离的情况下,两者交互只能通过json格式的数据,后端视图函数返回的数据应该是一个Json格式的大字典,那我们只能自己封装成大字典
from app01 import models
from django.http import JsonResponse
def ser_func(request):
# 1。查询所有的书籍对象
book_queryset = models.Book.objects.all() # 结果为QuerySet对象 [数据对象1,数据对象2]
# 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":{}...}
return JsonResponse(data_dict)
2.序列化组件
django自带的serializers.serialize()
方法
# 导入内置序列化模块
from django.core import serializers
def ser_func(request):
# 1。查询所有的书籍对象
book_queryset = models.Book.objects.all() # 结果为QuerySet对象 [数据对象1,数据对象2]
# serializers.serialize()方法第一个参数,是序列化数据的格式
res = serializers.serialize('json', book_queryset)
return HttpResponse(res)
二、批量操作数据
1.循环插入
直接循环插入,10s 500条左右,效率很低
def bulk_data_func(request):
for i in range(1, 10000):
models.Book.objects.create(title="第%s本书" % i)
book_queryset = models.Book.objects.all()
return render(request, 'bulkPage.html', locals())
2.orm提供的操作
# orm提供的批量查询
def bulk_data_func(request):
# 1.列表生成式生成对象,然后插入数据
book_obj_list = [models.Book(title="第%i本书" % i) for i in range(1, 10000)] # 通过类名加()生成对象
# 2 通过orm提供的批量操作插入
models.Book.objects.bulk_create(book_obj_list)
# 3.查询所有表中数据展示到前端
book_queryset = models.Book.objects.all()
return render(request, 'bulkPage.html', locals())
三、分页器
1.分页器思路
推导流程
1.queryset支持切片操作(正数)
2.研究各个参数之间的数学关系
每页固定展示多少条数据、起始位置、终止位置
3.自定义页码参数
current_page = request.GET.get('page')
4.前端展示分页器样式
5.总页码数问题
divmod方法
6.前端页面页码个数渲染问题
后端产生 前端渲染
- 分页器后端
# 分页器
def bulk_data_func(request):
# 1.查询出所有表中的数据,并展示到前端
# 3.获取书籍总数量
book_all = models.Book.objects.all()
book_count = book_all.count()
per_page_num = 10 # 没页展示多少数据
# 4.开始分页
all_page_num, extra_num = divmod(book_count, per_page_num)
if extra_num:
all_page_num += 1
current_page = request.GET.get('page', 1) # 获取'page'键对应的值,如果没有则默认为1
# 2.前端拿到的是字符串,所以需要转换成整型,并且需要异常捕获防止一样
try:
current_page = int(current_page)
except BaseException:
current_page = 1
start_num = (current_page - 1) * per_page_num
end_num = current_page * per_page_num
book_queryset = book_all[start_num:end_num]
# 5 在模版上通过添加标签,并通过过滤器取消转义添加分页页码
html_str = ''
real_page = current_page
if real_page<6:
real_page=6
for i in range(real_page - 5, real_page + 6):
if current_page==i:
html_str += '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i)
else:
html_str += '<li><a href="?page=%s">%s</a></li>' % (i, i)
return render(request, 'bulkPage.html', locals())
- 前端
{% for book_obj in book_queryset %}
<p class="text-center">{{ book_obj.title }}</p>
{% endfor %}
{{ html_str|safe }}
2.自定义分页器使用
- 新建utils文件夹的自定义py文件内
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=10, 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)
- view.py中
def ab_pg_func(request):
book_queryset = models.Books01.objects.all()
from app01.utils.mypage import Pagination
current_page = request.GET.get('page')
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())
{% for book_obj in page_queryset %}
<p>{{ book_obj.title }}</p>
{% endfor %}
{{ page_obj.page_html|safe }}
四、form组件
1.功能
- 自动校验数据
- 自动生成标签
- 自动展示信息
2.自动校验数据
(1)forms模块的关键字
- is_valid 是否合法,只要有一个不符合结果都是false
- cleaned_data 获取符合校验条件的数据
- errors 获取不符合校验规则的数据
(2)例
- views.py
class MyForm(forms.Form):
# 代表username字段最少三个字符最大八个字符
username = forms.CharField(min_length=3, max_length=8)
# age字段最小为0 最大为200
age = forms.IntegerField(min_value=0, max_value=200)
# email字段必须符合邮箱格式
email = forms.EmailField()
- 测试
# 测试views中的form组件
from app01 import views
form_obj = views.MyForm({'username':'jason','age':18,'email':'123'})
# 1.判断数据是否全部符合要求
res = form_obj.is_valid()
print(res) # False
# 2.获取全部符合校验条件的数据
res1 = form_obj.cleaned_data
print(res1) # {'username': 'jason', 'age': 18}
# 3.获取不符合校验规则的数据及其原因
res2 = form_obj.errors
print(res2)
# <ul class="errorlist"><li>email<ul class="errorlist"><li>Enter a valid email address.</li></ul></li></ul>
标签:内置,obj,self,Django,current,book,组件,pager,page
From: https://www.cnblogs.com/DuoDuosg/p/16995080.html