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.pswp.cn/news/280588.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280588.shtml
英文地址,請注明出處:http://en.pswp.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;你也可以將該…