0

我有点不知道为什么我不能让分页工作就是这种情况。

我在视图中完成了自定义 SQL 查询。

def latest_comments_view(request):
    from django.db import connection, transaction
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    from bicicleta.apps.comments.models import MPTTComment

    # Get the last comments, the last ones came first
    cursor = connection.cursor()
    cursor.execute("select dc.id as comment_id, em.id as main_id, es.n_section, dc.user_id, dc.user_name, dc.comment, dc.submit_date, cmptt.date_last_update, em.title as main_title, uu.profile_picture \
                    from django_comments dc \
                    join django_content_type dct on dc.content_type_id = dct.id \
                    join bicicletaengine_main em on em.id::int4 = dc.object_pk::int4 \
                    join comments_mpttcomment cmptt on cmptt.comment_ptr_id = dc.id \
                    join bicicletaengine_section es on es.id = em.section_id \
                    left join userprofile_userprofile uu on uu.user_id = dc.user_id \
                    where \
                    dc.is_public = 'true' \
                    order by dc.submit_date desc, cmptt.date_last_update asc") 
    comments = utils.dictfetchall(cursor)
    #pdb.set_trace()

    # Now, with the cursor above create the MPTTComment's objects
    mpttcomments = []
    for item in comments:
        mpttcomment = MPTTComment.objects.get(id=item['comment_id'])
        mpttcomments.append(mpttcomment)


    # Pagination
    paginator = Paginator(mpttcomments, 3)

    page = request.GET.get('pagina')
    try:
        comments = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        comments = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        comments = paginator.page(paginator.num_pages)

    return render_to_response('bicicletaengine/latest_comments/latest_comments.html', {'comments': comments, 'mpttcomments': mpttcomments}, context_instance=RequestContext(request))  

模板:

<div class="all-comments">
    {% for item in mpttcomments %}  {# {% for item in comments %}  #}

    {{ item.id }}

    {% endfor %}
    <div >
      <ul>
        {% if comments.has_previous %}
        <li><a href="?pagina={{ comments.previous_page_number }}">Página anterior</a></li>
        {% endif %}
        {% if comments.has_next %}
        <li><a href="?pagina={{ comments.next_page_number }}">Página seguinte</a></li>
        {% endif %}
      </ul>
    </div>      
</div>

症状是正确显示页数,但在每一页上我看到相同的结果。

有人可以给我一个线索吗?此自定义 SQL 查询是否只能与自定义管理器一起使用?

此致,

4

0 回答 0