渲染查询集的前几个项目,然后通过ajax加载更多项目

时间:2017-06-15 11:53:05

标签: jquery python ajax django

我想呈现Comment查询集的前5个注释。但是,当用户点击按钮时,我希望能够加载接下来的20条评论。

视图

def article(request, category, id):

    name = resolve(request.path).kwargs['category']
    instance = get_object_or_404(Post, id=id, entered_category=name)

    #comments
    current_page = int(request.GET.get('page_val', '1'))
    page_size = 5
    limit = page_size * current_page
    offset = limit - page_size

    new_comments_list = Comment.objects.filter(destination=id, parent_id=0).order_by('-timestamp')[offset:limit]

    counts = new_comments_list.count()
    total_pages = counts / page_size
    if counts % page_size != 0:
        total_pages += 1
    is_last = True if current_page >= total_pages else False

    comment_list = Comment.objects.filter(parent_id=0, post=post).order_by('-score__upvotes')[:2]

    context = {
        'id': id,
        'comment_list': new_comments_list,
        'is_last': is_last,
        'instance': instance,
    }
    if request.is_ajax():
        if new_comments_list:
            return render(request, 'list_ajax.html', context)
        else:
            return HttpResponse('last')

    return render(request, 'article.html', context)

comments_base.html

<div class="commentsContainer">

    {% include 'comments.html' %}
    #I can append the new comments here
    <p class="more_comments">more comments</p>
</div>

comments.html

{% block comments %}

    {% for i in comment_list %}
        {% if i.parent_comment %}
            <div class="comment_shell hasParent">
         {% else %}
            <div>
        {% endif %}
        <div class='comment_div' data-comment_id="{{ i.id }}">
            <div class="left_comment_div">
                <div class="username_and_votes">
                    <h3><a class='username_foreign'>{{ i.user }}</a></h3>
                    {% for j in i.score.all %}
                        <span class="upvotes">{{ j.upvotes }}</span>
                        <span class="downvotes">{{ j.downvotes }}</span>
                    {% endfor %}
                </div>
                <br>
                <p>{{ i.comment_text }}</p>
            </div>
        </div>
        {% include 'comments.html' with comment_list=i.replies.all %}
    </div>

    {% endfor %}


{% endblock %}

因此,您可以在我的观点中看到我只收到前5条评论。那么通过这样做,是否有任何可行的方法来加载查询集的下20个项目(通过AJAX)?或者,我应该最初加载整个查询集,但只显示前5个(通过jquery隐藏其余的)?然后通过jquery加载接下来的20条评论?或者这不可行?赞赏建议。

已编辑:我已添加完整代码。

2 个答案:

答案 0 :(得分:2)

你需要做自定义分页逻辑来实现你的目标。首先做一个分页逻辑并创建关于页面值的偏移和限制。这个逻辑的功能是使用相同的函数通过ajax使用django的内置方法附加数据<强> request.is_ajax()

def yourview(request):
    current_page = int(request.GET.get('page_val', '1'))
    page_size = settings.PAGE_SIZE_WEB (replace with your number e.g 5)
    limit = page_size * current_page
    offset = limit - page_size

    new_comments_list = Comment.objects.all()[offset:limit] #your query will return data accrodign page size and page no
    counts = Comment.objects.all().count()

    total_pages = counts / page_size
    if counts % page_size != 0:
        total_pages += 1
    is_last = True if current_page >= total_pages else False
    context = { 
           "new_comments_list":new_comments_list,
           "is_last":is_last  
      }

    if request.is_ajax():
        if new_comments_list:
            return render(request, 'comments.html', context)
        else:
            return HttpResponse('last')
    return render(request, 'article.html', context)

在模板中定义您的div,您可以在其中添加注释 的 article.html

<div class="comment-div">
  {% include 'comments.html' with is_last=is_last comment_list = comment_list %}  <!-- first time it will be loaded with page no 1 and when you call jquery it will be loaded with respective page number. -->
</div>
 <input type="hidden" id="page_val" value="2" /> <!-- setting page no according jquery calls ( by default it will be 2 for getting next comment data ) --> 

comments.html 文件,

{% for i in comment_list %}
    {{ i }}
{% endfor %}

使用jquery逻辑来附加数据, 的 yourfilename.js

$(body).on('click','#append_data',function(){
      var page_val = $('#page_val').val();
      $.ajax({
        url: "/yoururl",
        type: "GET",
        data: {"page_val":page_val},
        success: function (data) {
            if (data != "last") {
                page_val++;
                $('#page_val').val(page_val); #need to increment page no to get incremented number to get next page data
                #append your data on comment-div
            }
            else if (data == "last" ) {
                #hide show more comments
             }
        })
})

答案 1 :(得分:0)

你应该创建新的视图功能,返回文章的评论,然后我建议使用django-el-pagination app为你起什么作用。