假设我有这段代码:
# 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
如何将信息添加到线程列表中的线程,就像代码示例中的某些内容一样?我不想更新数据库,只是在为用户显示数据之前操纵数据。
答案 0 :(得分:3)
您展示的示例代码很好,至少在一般情况下如此。一旦开始迭代查询集,Django将创建内存模型实例,并且可以像任何其他Python对象一样将属性添加到内存版本中。
为了能够根据第二个qs编辑第一个qs中的线程:
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