创建一个字典,键为属性,值为模型 object

create a dictionary of with key as the attribute and value as model object

说我有这个 table:

class Blog(models.Model)
  title = models.CharField()
  body = models.CharField()
  author = models.ForeignKey(Author)

我需要创建 3 行标题 (title_1、title_2、title_3)。我需要获取所有博客 object 并创建一个字典,其中键作为标题,值作为博客 object。

blog_dict = {'title_1': <blog_object_1>, 'title_2': <blog_object_2>, 'title_2': <blog_object_3>}

我有 100 万条记录要处理。有什么有效的方法吗?

这可能会完成这个任务

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}

我发现第一种方法更适合初学者,但也值得一提的是另一种方法。

如果我的理解是正确的,您希望创建一个字典,基本上将每个博客对象的名称映射到实例,对吗?这实际上取决于您使用的特定功能以及您如何创建字典。我要做的是在初始化每个对象时创建字典,而不是在创建对象后对其进行迭代,但这假设您可以访问 class 的 init 函数并且不需要这些对象来做任何事情,直到这个观点。我不太清楚你说的“I need to create 3 rows”和“I have 1 million records to work.”是什么意思,所以我不能给你一个确切的方法来尝试。让我们假设您的意思是您想要将 100 万条记录分成 table,即 (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 库,它们可以帮助解决这个问题。我知道双端队列在弹出时提供更快的速度 left/right 但我不知道有什么可以加快它的速度。

此外,如果您知道对象的确切数量,则可以在执行任何操作之前将 space 预先分配给列表,然后通过索引修改列表,这比追加更快:请参阅 this link. link 还表明列表理解可以更快,但我从经验中知道,您应该始终自己比较时间,因为这取决于您如何使用不同的方法。