-2
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()

我想手动将新项目添加到列表中。

4

2 回答 2

0

您的问题写得不好,但我相信您正在寻找的是annotation此处的文档):

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'

返回的值不是字典列表,而是 a queryset,它是对象的可迭代对象。然后,您可以post_count作为属性访问:

thread_list[0].post_count
于 2013-10-28T11:50:20.447 回答
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”

于 2013-10-29T08:29:33.837 回答