【问题标题】:create a dictionary of with key as the attribute and value as model object创建一个以键为属性,以值为模型对象的字典
【发布时间】:2022-01-03 07:11:45
【问题描述】:

假设我有这张桌子:

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

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

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

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

【问题讨论】:

  • 为什么你需要像title_1 e.t.c 这样的密钥,为什么不列出对象似乎没有必要?能具体点吗?

标签: python python-3.x django django-models django-views


【解决方案1】:

这可能会完成这项任务

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}

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

【讨论】:

  • 不使用for循环可以吗?
  • 我不这么认为,但也许有办法
  • 我必须等待我的声誉达到 50 才能发表评论,但您可以使用这样的 dict 理解跳过 for 循环:blog_dict = { blog.title:blog for blog in blogs}
  • 它也是一个 for 循环,但合并在一行中,但它会执行相同的过程......我更喜欢使用完整的形式,因为他在他的问题中说他很新蟒蛇
【解决方案2】:

如果我理解你是正确的,你希望创建一个字典,基本上将每个博客 obj 的名称映射到实例,对吗?这将真正归结为您使用的特定功能以及您如何创建字典。我要做的是创建字典,同时您初始化每个对象,而不是在创建它们后对其进行迭代,但这假设您可以访问该类的 init 函数并且在此之前不需要其他任何对象。我不太清楚你所说的“I need to create 3 rows”和“I have 1 million records to work.”是什么意思,所以我不能给你一个确切的方法来尝试。让我们假设您的意思是将 100 万条记录划分为 (1mil/3) 列 x 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 库。我知道双端队列在左/右弹出时提供更快的速度,但我不知道有什么可以加快速度。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多