循环/更改对象列表中某些对象的最佳方法

2024-04-24 17:00:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个代码:

# Get 30 threads
threads = Thread.objects.all()[:30]
threads_id = [o.pk for o in threads]
# Extra info about threads that the user have visited
visited_threads = VisitedThread.objects.filter(pk__in=threads_id, user=request.user)

# I want to loop the visited_threads and add info to thread in threads with new info
for visited_thread in visited_threads:
    # Here I want to add things to thread (visited_thread.thread), something like:
    # thread.has_unread_post = thread.post_count > visited_thread.post_count

如何向threads列表中的线程添加信息,如代码示例中的某些内容?我不想更新数据库,只是在向用户显示数据之前对其进行操作。你知道吗


Tags: theto代码ininfoidforobjects
1条回答
网友
1楼 · 发布于 2024-04-24 17:00:24

您展示的示例代码很好,至少在一般意义上是这样的。一旦您开始迭代queryset,Django将创建内存中的模型实例,并且您可以像任何其他Python对象一样向内存中的版本添加属性。你知道吗

要基于第二个Q编辑第一个Q中的线程,请执行以下操作:

threads = Thread.objects.all()[:30]
threads_by_pk = dict((t.pk, t) for t in threads)
# Extra info about threads that the user have visited
visited_threads = VisitedThread.objects.filter(pk__in=threads_by_pk.keys(), user=request.user)

# I want to loop the visited_threads and add info to thread in threads with new info
for visited_thread in visited_threads:
    thread = threads_by_pk[visited_thread.pk]
    thread.has_unread_post = thread.post_count > visited_thread.post_count

相关问题 更多 >