是否可以使用AJAX更改查询集?

时间:2017-02-06 22:09:27

标签: python ajax django django-queryset

我有用于评论的查询集,如下所示:

comment_list = Comment.objects.filter().order_by('-score__upvotes')
new_comments_list = Comment.objects.filter().order_by('-timestamp')

然后我的模板是

{% for comment in comment_list %}
    {{ comment }}

...

有没有办法使用AJAX(无页面刷新)将{% for comment in comment_list %}更改为{% for comment in new_comments_list %}

或者可能将comment_list的值更改为等于Comment.objects.filter().order_by('-timestamp')

1 个答案:

答案 0 :(得分:1)

当开发人员(您)这样说时,会发生AJAX请求。例如,如果您在“单击”某个特定按钮上设置了一个事件监听器来发出AJAX请求,那么将会发出一个AJAX请求。

假设您有一个事件监听器,用id=my-button“监听”特定按钮上的点击事件。

{# Place this as a separate html file, say "ajax_comments.html" #}
<div id="my-placeholder">
    {% for comment in comments %}
        {{ comment }}
    {% endfor %}

    <button id="my-button">Update comments</button>
</div>
{# END OF PLACE THIS #}

{# ############################################################### #}

{# Begin of your main HTML template, say "my_template.html" #}

....

{% include 'path/to/ajax_comments.html' %}

.... 

// make an Ajax call (GET request) to the same url, using jQuery.
$(document).ready(function() {
    $('#my-button').on('click', function() {
        $.ajax({
            'method': 'GET',  // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too!
            'url': '.',  // submit to the same url
            'data': {},  // pass here any data to the server. You can omit it.
            success: function(dataReturned) {
                // This function will run when server returns data
                $('#my-placeholder').replaceWith(dataReturned);
            }
        });
    });
});

{# END OF "my_template.html" #}

完成HTML,JS。现在转到views.py

def my_view(request):
    if request.is_ajax():
        # If you have passed any data through the 'data' property 
        #you can get it here, according to the method used.
        my_data = request.GET.get('data-name')
        comments = Comment.objects.filter().order_by('-timestamp')
        # Note that we are passing the 'ajax_comments.html' template.
        return render(request, 'ajax_comments.html', {'comments': comments})

    comments = Comment.objects.filter().order_by('-score__upvotes')
    return render(request, 'my_template.html', {'comments': comments})
  1. 按钮在模板中按下
  2. 向您的服务器发出AJAX请求
  3. 在您的观看中,您处理此类请求,并返回包含新查询集的HTML部分。
  4. 此返回不会直接呈现给模板,而是转到$.ajax()等待此功能的函数。
  5. 一旦收到,它就会按照我们写的要做(用新的div替换var createAttachmentsForMail = function (files) { var attachmets = []; files.forEach(function (value) { attachmets.push( { "Content-type": mime.lookup(value), "FileName": path.basename(value), "content": new Buffer(fs.readFileSync(value)).toString('base64') } ); }); return attachmets; }; 的数据)
  6. 希望这能帮到你!