django11:自动序列化/批量插入数据/分页器

自动序列化

借助serializers帮你自动完成序列化

from app01 import models
from django.core import serializers
def ab_se(request):user_queryset = models.Userinfo.objects.all()#原始方法user_list = []for user_obj in user_queryset:user_list.append({'username':user_obj.username,'password':user_obj.password,'gender':user_obj.get_gender_display(),})res = json.dumps(user_list)#方法****2res = serializers.serialize('json',user_queryset)  # 序列化return HttpResponse(res)

 

批量插入数据

models.Book.objects.bulk_create(book_list)
 

分页器

#原始分页 切片
book_queryset=models.Book.objects.all()[0:10]

自定义

补充:

封装代码的思路

1.先用最粗糙的代码实现功能

2.在功能基础上,再考虑优化

a.先函数

b.在对象

并不一定要面向对象

 

用到非django内置的第三方功能或组件代码时,

一般创建utils文件夹,一般在project根目录,在文件夹内对模块进行功能性划分

utils可以在每个应用创建,具体看实际情况。

class

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:  最多显示的页码个数用法:queryset = model.objects.all()page_obj = Pagination(current_page,all_count)page_data = queryset[page_obj.start:page_obj.end]获取数据用page_data而不再使用原始的queryset获取前端分页样式用page_obj.page_html"""try:current_page = int(current_page)except Exception as e:current_page = 1if current_page <1:current_page = 1self.current_page = current_pageself.all_count = all_countself.per_page_num = per_page_num# 总页码all_pager, tmp = divmod(all_count, per_page_num)if tmp:all_pager += 1self.all_pager = all_pagerself.pager_count = pager_countself.pager_count_half = int((pager_count - 1) / 2)@propertydef start(self):return (self.current_page - 1) * self.per_page_num@propertydef end(self):return self.current_page * self.per_page_numdef page_html(self):# 如果总页码 < 11个:if self.all_pager <= self.pager_count:pager_start = 1pager_end = self.all_pager + 1# 总页码  > 11else:# 当前页如果<=页面上最多显示11/2个页码if self.current_page <= self.pager_count_half:pager_start = 1pager_end = self.pager_count + 1# 当前页大于5else:# 页码翻到最后if (self.current_page + self.pager_count_half) > self.all_pager:pager_end = self.all_pager + 1pager_start = self.all_pager - self.pager_count + 1else:pager_start = self.current_page - self.pager_count_halfpager_end = self.current_page + self.pager_count_half + 1page_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 get_book(request):book_list = models.Book.objects.all()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>

 

 

参考:

https://www.cnblogs.com/guyouyin123/p/12173020.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280588.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

罗汉塔最少步骤_如何以最少的步骤压缩和密码保护文件?

罗汉塔最少步骤If you have a large batch of files to compress and you want to add password protection to each of them, what is the simplest or quickest way to do so? Today’s SuperUser Q&A post has the answer to a curious reader’s question. 如果要压缩…

IoTSharp中使用X509加密MQTT通讯并实现设备鉴权

IoTSharp支持MQTT协议通过 TLS 1.2 加密通讯&#xff0c; 并可以通过X509证书进行设备认证登录。基本配置在 appsettings.Production.json中需要 指定域名&#xff0c; 并设置EnableTls为true"MqttBroker":{"DomainName":"http://demo.iotsharp.net:2…

IBM希望其“裁剪”过的Swift能够引诱你使用BlueMix云

现在所有人都可以使用了——微软顶尖的工程师表示&#xff0c;“呼吸新鲜的空气吧&#xff01;” 据Stack Overflow的估计&#xff0c;Swift在最受欢迎的编程语言中排名第二&#xff0c;该语言已经出现在了IBM的BlueMix云平台之上&#xff0c;供所有人使用。 她从今年二月份开始…

物理层、数据链路层、介质访问控制子层

物理层 物理层定义了比特作为信号在信道上发送时相关的电气、时序和其它接口&#xff0c;物理层是构建网络的基础。数据通信理论基础&#xff1a;改变诸如电压或者电流等某种物理特性的方法可用来在电线上传输信息&#xff0c;如果用一个以时间t为自变量的单值函数 f(t) 来表示…

如何批量删除指定的GitHub Repos

正常情况下&#xff0c;如果需要删除GitHub上不需要的repos&#xff0c;手动删除的操作有点繁琐。如果只要删除一个还能接受&#xff0c;手动删除多个repos就有点浪费时间了。其实我们可以通过GitHub的API接口来批量删除不需要的repos。 将要删除的repos按照username\repos-nam…

django12:form 组件/渲染标签/数据校验/钩子函数/

基本用法 from django import forms# 自己写一个类 class RegForm(forms.Form):username forms.CharField(min_length3,max_length8, label"用户名")password forms.CharField(min_length3,max_length8,label"密码")emailforms.EmailField() 1.校验数据为…

如何快速拥有一个 Web IDE

本文将介绍如何使用 2-3 句指令在几分钟内创建一个 Web IDE 环境。服务器准备如何准备服务器可以参考上文 一键体验 Istio&#xff0c;这里只需要一台即可&#xff0c;示例中的服务器 IP 为&#xff1a;43.154.189.116安装 Web IDE下载安装工具在服务器上&#xff0c;执行以下指…

有了防火墙、IPS、WAF 还需要数据库审计?

本文讲的是 有了防火墙、IPS、WAF 还需要数据库审计&#xff1f;&#xff0c;“我们的网络安全系统中已经有了Web应用防火墙、网络防火墙和IPS&#xff0c;难道还需要数据库审计吗&#xff1f;”很多人有这样的疑问&#xff0c;网络中有层层防护&#xff0c;还不能保护数据库的…

20155339 Exp4 恶意代码分析

20155339 Exp4 恶意代码分析 实验后回答问题 &#xff08;1&#xff09;如果在工作中怀疑一台主机上有恶意代码&#xff0c;但只是猜想&#xff0c;所有想监控下系统一天天的到底在干些什么。请设计下你想监控的操作有哪些&#xff0c;用什么方法来监控。 监控网络连接。当某个…

Linux就该这么学---第七章(LVM逻辑卷管理器)

第七章节-LVM技术逻辑卷管理器(LVM,Logical Volume Manager)1.物理卷(PV,physical Volumn)2.卷组(VG,Volume Group)3.逻辑卷(LV,Logical Volume)基本单元[PE,Physical Extent] 物理卷处于LVM中的最底层&#xff0c;可以将其理解为物理硬盘、硬盘分区或者RAID磁盘阵列卷组建立在…

django13:Session与Cookie操作

Session与Cookie cookie 服务端保存在客户端浏览器上的信息都可以教cookie 表现形式一般是k:v键值对&#xff08;可以多个&#xff09; 优化&#xff1a; 随机字符串1&#xff1a;用户1相关信息 随机字符串2&#xff1a;用户2相关信息 session 数据是保存在服务端 表现形…

从Windows XP升级? 这是您需要了解的Windows 7

With Windows XP reaching the end of its long support life, many businesses and individuals are avoiding Windows 8 and upgrading to Windows 7 instead. If you’re a latecomer to Windows 7, here are the basics you need to know. 随着Windows XP使用寿命的延长&am…

Java迭代器原理

1迭代器模式 迭代器是一种设计模式&#xff0c;这种模式用于顺序访问集合对象的元素&#xff0c;不需要知道集合对象的底层表示。 一般实现方式如下&#xff1a;&#xff08;来自&#xff09; public interface Iterator {public boolean hasNext();public Object next(); } pu…

企业版Java EE正式易主 甲骨文再次放手

有人说甲骨文收购的东西大多没有了好下场&#xff0c;这么说虽然有些片面&#xff0c;但是最近一个月Java EE和Solaris的境遇难免让人产生类似的联想。 继笔者上次报道《甲骨文将放弃Java EE 开源基金会双手欢迎》之后&#xff0c;最新消息显示&#xff0c;原本在甲骨文手中的J…

js中各种位置

js中各种位置 js中有各种与位置相关的属性,每次看到的时候都各种懵逼。索性一次总结一下。 clientHeight 内容可视区域的高度。包括padding不包括border、水平滚动条、margin。对于inline的元素这个属性一直是0&#xff0c;单位px&#xff0c;只读元素。offsetHeight offsetHei…

如何判断您是否拥有32位或64位版本的Google Chrome浏览器

Google Chrome is extremely popular with our readers, but did you know that they also have a 64-bit version of the browser these days? Here’s how to tell which version you are running, and how to switch if you aren’t. 谷歌浏览器在我们的读者中非常受欢迎&a…

django14:CBV加入装饰器

加在方法上面 from django.utils.decorators import method_decoratorclass HomeView(View):def dispatch(self, request, *args, **kwargs):return super(HomeView, self).dispatch(request, *args, **kwargs)def get(self, request):return render(request, "home.html&…

Kubernetes 跨集群流量调度实战 :访问控制

背景众所周知&#xff0c;Flomesh 的服务网格产品 osm-edge[1] 是基于 SMI&#xff08;Service Mesh Interface&#xff0c;服务网格接口&#xff09; 标准的实现。SMI 定义了流量标识、访问控制、遥测和管理的规范。在 上一篇 中&#xff0c;我们体验过了多集群服务&#xff0…

python下sqlite增删查改方法(转)

sqlite读写 #codingutf-8 import sqlite3 import os #创建数据库和游标 if os.path.exists( test.db):connsqlite3.connect( test.db)curconn.cursor() else:connsqlite3.connect( test.db)curconn.cursor()#创建表 cur.execute(CREATE TABLE IF NOT EXISTS customer (ID VARCH…

Apache HTTP Server 与 Tomcat 的三种连接方式介绍

本文转载自IBM developer 首先我们先介绍一下为什么要让 Apache 与 Tomcat 之间进行连接。事实上 Tomcat 本身已经提供了 HTTP 服务&#xff0c;该服务默认的端口是 8080&#xff0c;装好 tomcat 后通过 8080 端口可以直接使用 Tomcat 所运行的应用程序&#xff0c;你也可以将该…