說我有這張桌子:
class Blog(models.Model)
title = models.CharField()
body = models.CharField()
author = models.ForeignKey(Author)
我需要用標題(title_1、title_2、title_3)創建 3 行。我需要獲取所有博客物件并創建一個以鍵為標題和值作為博客物件的字典。
blog_dict = {'title_1': <blog_object_1>, 'title_2': <blog_object_2>, 'title_2': <blog_object_3>}
我有 100 萬條記錄要處理。有什么有效的方法可以做到嗎?
uj5u.com熱心網友回復:
這可能會完成這項任務
blog_dict = {}
blogs = Blog.objects.all()
for blog in blogs:
blog_dict[blog.title] = blog
正如@ZXYNINE 在下面的評論部分中提到的,它可以用一行來完成,而不是像這樣的完整形式的 for 回圈:
blog_dict = { blog.title:blog for blog in blogs}
我發現第一種方法更適合初學者,但也值得一提另一種方法。
uj5u.com熱心網友回復:
如果我理解正確,您希望創建一個 dict 來將每個博客 obj 的名稱映射到實體,對嗎?這將真正歸結為您使用的特定功能以及您如何創建字典。我會做的是在初始化每個物件的同時創建字典,而不是在它們創建后迭代它們,但假設您可以訪問類的 init 函式并且在此之前不需要其他任何物件的物件。我不太清楚“ I need to create 3 rows”與“ I have 1 million records to work.”的組合是什么意思,所以我不能給你一個確切的嘗試方法。讓我們假設您的意思是您想將 100 萬條記錄劃分到一個表中,該表是 (1mil/3) 列乘以 3 行。我會做這樣的事情:
class Blog(models.Model):
title = models.CharField()
body = models.CharField()
author = models.ForeignKey(Author)
Blogs:'list[Blog]' = [Blog,]*1000000
BlogTable = []
BlogRowBuffer = {}
# Using an int to count instead of len(BlogRowBuffer) to save processing power
BlogRowCount = 0
for blog in Blogs:
BlogRowBuffer[blog.title] = blog
BlogRowCount =1
#Once you add the third item to the row buffer, the buffer is made into a column in the table.
# And the values reset to start all over.
if BlogRowCount == 3:
BlogTable.append(BlogRowBuffer)
BlogRowBuffer = {}
BlogRowCount = 0
問題是,無論您如何解決它,您都必須迭代超過 100 萬個物件,而這總是需要相當長的時間。您應該盡可能使用內置的 Python 函式,因為它們是用 C 撰寫的,并且通常比其他任何函式都快得多。您還應該查看一些可以幫助解決此問題的 python 庫。我知道 deque 在向左/向右彈出時提供更快的速度,但我不知道有什么可以加快速度的。
此外,如果您知道物件的確切數量,您可以在執行任何操作之前為串列預先分配空間,然后只需通過索引修改串列,這比附加更快:請參閱此鏈接。該鏈接還表明串列理解可以更快,但我從經驗中知道您應該始終自己比較時間,因為這取決于您如何使用不同的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403009.html
標籤:
上一篇:例外:匹配查詢不存在
