Zorgan Zorgan - 1 year ago 81
Python Question

How do I change my queryset using AJAX?

I want to be able to change my comments queryset without page refresh. Here are the querysets:

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


Then my template is

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

...


Is there any way to change
{% for comment in comment_list %}
to
{% for comment in new_comments_list %}
using AJAX (no page refresh)?

Or possibly changing the value of
comment_list
to equal
Comment.objects.filter().order_by('-timestamp')
?

Answer Source

What I guess, you are trying to use comment_list when page renders and new_comment_list using ajax without modifying

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

The problem with your code is comment_list is a queryset and it is evaluated on the server side, when the page is rendered (after passing through Django template engine ).Javascript doesn't understand queryset. It understands HTML or JSON. So, you have to modify your script so that it return HTML or JSON for ajax request.

I would suggest you re-write your view like:

from django.template.loader import render_to_string

if request.is_ajax(): 
     new_comments_list = Comment.objects.filter().order_by('-timestamp')
     html = render_to_string('your_template', {'comment_list': new_comments_list})
     return HttpResponse(html)

And write your frontend to generate this HTML code. here is a link that gives more better explanation of rendering using ajax: Returning Rendered Html via Ajax

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download