Django - реализовать вложенный цикл в функции ajax
У меня есть приложение Django (3.2) и я пытаюсь реализовать фильтры в Ajax в jquery, который будет фильтровать все продукты на основе выбранных фильтров.
Проблема в том, что Ajax фильтрует только области, а не потребности и продукты. Как я могу реализовать вложенный цикл в Ajax, чтобы он работал так же, как мой product_list, и я видел не всю область, а только соответствующие продукты?
views.py
def filter_data(request):
client_type = request.GET.getlist('client_type[]')
business_challange = request.GET.getlist('business_challange[]')
product_list = Area.objects.prefetch_related(Prefetch("need_area", queryset=Need.objects.filter(category_need__product__isnull=False,category_need__product__status=1).distinct())).filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct()
if len(client_type) > 0:
product_list = product_list.filter(need_area__category_need__product__client_type__title__in=client_type).distinct()
if len(business_challange) > 0:
product_list = product_list.filter(need_area__category_need__product__business_challange__title__in=business_challange).distinct()
context = {
'areas': product_list,
}
ajax_template = render_to_string('product-list-ajax.html', context)
return JsonResponse({'data': ajax_template})
product-list-ajax.html
{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
<h2 class="fw-bold my-2">{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 class="text-muted mt-4">{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.product.all %}
<a href="{{product.get_absolute_url}}" class="pe-2"><span>{{product.title}}</span></a>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
product-filters.js
$(document).ready(function(){
$(".ajaxLoader").hide();
$(".form-check-input").on('click', function(){
var filterObj={};
$(".form-check-input").each(function(index,ele){
var filterVal=$(this).val();
var filterKey=$(this).data('filter');
filterObj[filterKey]=Array.from(document.querySelectorAll('input[data-filter='+filterKey+']:checked')).map(function(el){
return el.value;
});
});
//Ajax
$.ajax({
url: 'filter-data',
data: filterObj,
dataType: 'json',
beofreSend: function(){
$(".ajaxLoader").show();
},
success: function(res){
$("#filteredProducts").html(res.data);
$(".ajaxLoader").hide();
console.log(res)
}
});
});
});