django-voting 与分页器相结合:类型为 'generator' 的 TypeError 对象没有 len()



更新

我所要做的就是根据对象的投票分数获得对象列表,并将其发送到模板中。如果你以前使用过django投票,请帮我弄清楚这个。我需要一个列表,因为我将该列表传递给paginator应用程序。

我应该问一个不同的问题吗(也许可以结束这个问题(


我试图按照分数的顺序获取所有对象,将它们附加到列表中,并将其发送到模板中,但我遇到了错误。你能给我看一个按投票分数排序的快速检索对象的方法吗?

get_top()方法来自django投票应用程序经理:在github:上链接该方法

https://github.com/brosner/django-voting/blob/master/voting/managers.py#L122

我在我的视图中得到的所有评论为:

comments_all = Vote.objects.get_top(Comment, 100, False) 
"""URL param is latest, then sort by datetime
else sort by vote count, default"""
if sort == 'latest':
    comments_all = Comment.objects.filter(book=book_id, active=True)
    .order_by('-created_datetime', '-modified_datetime')
else:
    comments_all = Vote.objects.get_top(Comment, 100, False)
"""Pagination: if there is no page, set it to 1"""
comments_paginator = Paginator(comments_all, 20)
try:
    page = int(request.GET.get('page', '1'))
except ValueError:
    page = 1
#pagination: get the pages.
try:
    comments_page = comments_paginator.page(page)
except (EmptyPage, InvalidPage):
    comments_page = comments_paginator.page(comments_paginator.num_pages)

错误跟踪:

    Traceback:
    File "/Users/AJ/work/projects/virtual_environments/bottledink/lib/python2.6/site-    packages/django/core/handlers/base.py" in get_response
    111. response = callback(request, *callback_args,   **callback_kwargs)
    File "/Users/AJ/work/projects/bottledink/../bottledink/main/views.py" in show_book
    74.  comments_page = comments_paginator.page(page) 
    File "/Users/AJ/work/projects/virtual_environments/bottledink/lib/python2.6/site-packages/django/core/paginator.py" in page
    37. number = self.validate_number(number)
    File "/Users/AJ/work/projects/virtual_environments/bottledink/lib/python2.6/site-packages/django/core/paginator.py" in validate_number
    28.   if number > self.num_pages:
    File "/Users/AJ/work/projects/virtual_environments/bottledink/lib/python2.6/site-packages/django/core/paginator.py" in _get_num_pages
    60.  if self.count == 0 and not self.allow_empty_first_page:
    File "/Users/AJ/work/projects/virtual_environments/bottledink/lib/python2.6/site-packages/django/core/paginator.py" in _get_count
    53.   self._count = len(self.object_list)
Exception Value: object of type 'generator' has no len()

更新:我尝试过:

comments_all = list(Vote.objects.get_top(Comment, 100, False))

但它给出了错误:

int() argument must be a string or a number, not 'tuple'

尝试做:

comments_paginator = Paginator(list(comments_all), 20)

http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-关系与聚合Django的数据库聚合API不适用于GenericRelation

您可以使用https://github.com/coleifer/django-generic-aggregation

from django.contrib.comments.models import Comment
from django.db.models import Sum
from generic_aggregation import generic_annotate
from voting.models import Vote
#want might to filter on is_public and is_removed
top = generic_annotate(Comment.objects.all(), Vote.object, Sum('vote')).filter(active=True)