thread_list = thread.objects.select_related().filter(thread_forum_id = current_obj.id).order_by('-thread_date')
for thread in thread_list:
count = post.objects.select_related().filter(post_thread_id = thread.id).count()
thread.post = count
怎么做?
thread.post = count
^
class thread(models.Model):
mess = models.CharField(max_length=5000)
objects = thread_manager()
我想手动将新项目添加到列表中。
答案 0 :(得分:0)
您的问题写得不好,但我相信您所寻找的是annotation
(docs here):
from django.db.models import Count
thread_list = thread.objects.select_related().filter(thread_forum_id=current_obj.id) \
.order_by('-thread_date').annotate(post_count=Count('post_thread_set'))
# I'm just guessing this name: 'post_thread_set'
返回的值不是dicts列表,而是queryset
,它是一个可迭代的对象。然后,您可以访问post_count
作为属性:
thread_list[0].post_count
答案 1 :(得分:0)
你的方式很好。 但是存在冲突:
thread_list = thread.objects.select_related().filter(thread_forum_id = current_obj.id).order_by('-thread_date')
for thread in thread_list:
count = post.objects.select_related().filter(post_thread_id = thread.id).count()
thread.post = count
您的班级名称为主题,您的循环名称类似于班级。 对于thread_list中的线程:
就这样做:
for threads in thread_list:
count = post.objects.select_related().filter(post_thread_id = threads.id).count()
threads.post = count
或类似的东西。只需更改循环 - 我在单词的末尾添加's'