Django内置序列化组件
我们在学习Django内置序列化组件之前需要知道的一点是:前后端分离的项目,它的视图函数只需要返回json格式的数据即可
from django.http import JsonResponse
1.不适用序列化组件
JsonResponse发送到前端的数据是以字典形式发送的,所以正常情况下如果我们想将数据以json格式通过JsonResponse发送到前端需要将数据转为字典格式
eg:
def ad_set_func(request):
book_queryset = models.Book.objects.all()
data_dict = {}
for book_obj in book_queryset:
temp_dict = {}
temp_dict['pk'] = book_obj.pk
temp_dict['name'] = book_obj.name
temp_dict['price'] = book_obj.price
data_dict[book_obj.pk] = temp_dict
return JsonResponse(data_dict)
2.使用序列化组件(django自带的)
def ad_set_func(request):
book_queryset = models.Book.objects.all()
# 导入内置的序列化模块
from django.core import serializers
# 调用该模块下的方法,第一个参数是我们希望以什么样的方式序列化数据
res = serializers.serialize('json', book_queryset)
return HttpResponse(res)
注意:无论我们以哪种方式传json数据,汉字都会变成二进制编码,需要我们自己解码
批量操作数据
需求:现在有一张books表,需要往该表中插入10万条数据
1.使用for循环
def insert_data(request):
for i in range(1, 100000):
models.Books.objects.create(name='第%s本书' % i)
book_queryset = models.Books.objects.all()
return render(request, 'datapage.html', locals())
使用for循环往表中批量插数据速度会非常慢,数据量小的情况下还好,数据量一旦很大就会很慢
2.使用ORM提供的批量插入操作 bulk_create()
def insert_data(request):
book_obj_list = [] # 也可以使用列表生成式
for i in range(1, 100000):
book_obj = models.Book01(name='第%s本书' % i) # 单纯的用类名加括号产生对象
book_obj_list.append(book_obj)
models.Book01.objects.bulk_create(book_obj_list) # 使用ORM提供的批量插入操作
book_queryset = models.Books.objects.all()
return render(request, 'datapage.html', locals())
自定义分页器的使用
django自带分页器模块但是使用起来很麻烦 所以我们自己封装了一个,我们自己封装的模块可以创建一个自定义的py文件用来存储
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.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)
if current_page > all_pager:
current_page = 1
self.current_page = current_page
@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)
input_page = '<li><form action="" method="post"><input type="text" name="page"><input type="submit"></form></li>'
page_html_list.append(input_page)
# 尾部添加标签
page_html_list.append('''
</nav>
</ul>
''')
return ''.join(page_html_list)
后端使用
def get_book(request):
book_list = models.Book.objects.all()
if request.method == 'POST':
current_page = request.POST.get('page')
else:
current_page = request.GET.get("page", 1)
all_count = book_list.count()
page_obj = Pagination(current_page=current_page,all_count=all_count,per_page_num=10)
page_queryset = book_list[page_obj.start:page_obj.end]
return render(request,'booklist.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>