Home > Enterprise >  How to return queryset using AJAX in django?
How to return queryset using AJAX in django?

Time:11-16

Here is my view.py :

def get_group_ajax(request):
    if request.method == "GET":
        g_id = request.GET['group_id']
        productlist = models.Stocksupporter.objects.filter(pmaingroups = g_id).values('productname').exclude(numberqut=0) *//This is my queryset*

Here is my AJAX and used Django template for loop :

$("#allgrp").change(function () {
    const gId = $('#allgrp').val();

    $.ajax({
      type: "GET",
      url: '{% url "webapp:get_group_ajax" %}',
      data: {
        'group_id': gId,
      },
      success: function (data) {
          html_data = 
          `
          {% for pr in productlist %}
          <div  id="card_id">
            <p>{{ pr.productname }}</p>
          </div>
          {% endfor %} 
           `;
         
          $("#card_id2").html(html_data);
      }
    });
  });

now what is problem: I want return productlist (for loop) in AJAX Success based on selected value (mean group id), i used Response methods but still can not return anything. is there any way for do it?

CodePudding user response:

views.py :

from django.http import JsonResponse

if 'group_id' in request.GET:
    productlist = Stocksupporter.objects.filter(pmaingroups = g_id).exclude(numberqut=0).values('productname')
    return JsonResponse(list(productlist ),safe=False)

Success function in html:

function(productListData){
   for(i in productListData){
     let element = ` <div >
        <p>${productListData[i].productname}</p>
      </div>`
      $("#card_id2").append(element);
    }
 }
  • Related