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

标签 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')

最佳答案

当开发人员(您)这么说时,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. 在您的 View 中,您可以处理此类请求并返回带有新查询集的 HTML 部分。
  4. 此返回不会直接呈现到模板,而是转到等待此返回的 $.ajax() 函数。
  5. 收到后,它会执行我们编写的操作(用新数据替换 div 的数据)

希望这对您有帮助!

关于python - 是否可以使用 AJAX 更改查询集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42078170/

相关文章:

php - 在 javascript 调用中从 mysql 数据库中选择

javascript - 如何使 ajax 内容被谷歌索引?

带时间戳的 Django 过滤器模型

django - 序列化程序 ForeignKey 结果为 "Expected a dictionary ..."

python - 在 Python smtplib 中附加一个 txt 文件

Python Azure Web作业传递参数

python - 如何选择数值最大的列名作为新的列元素?

php - AJAX 表单仅重新加载页面

javascript - 如何将数据从ajax传递到django View ?

python - cqlsh::ImportError:无法导入名称 cql_keywords_reserved