Getting query length with Ajax / Django

41 Views Asked by At

According to the selection in the form, I want to get the number of records that match the id of the selected data as an integer.

Here is my view :

def loadRelationalForm(request):
    main_task_id = request.GET.get('main_task_id')
    relational_tasks = TaskTypeRelations.objects.filter(main_task_type_id = main_task_id)
    data_len = len(relational_tasks)


    return JsonResponse({'data': data_len})

Here is my ajax :

<script>
$("#id_user_task-0-task_types_id").change(function () {
    const url = $("#usertask-form").attr("data-relationalform-url");  
    const mainTaskId = $(this).val();  
    
    $.ajax({                    
        url: url,                 
        data: {
            'main_task_id': mainTaskId,             
        },
        success: function (resp) {  
           console.log(resp.data);
        }
    });

});

I want to write the number of relational tasks associated with the main_task_id of the selected data in the form. But I couldn't do it. Thanks for your help. Kind regards

1

There are 1 best solutions below

4
On

Make sure the data you're pulling is an integer. This line :

 main_task_id = request.GET.get('main_task_id')

Might be a string, and the resulting query would find no match.

Aside, if you want a number of related objects, you have more efficients way to do it :

def loadRelationalForm(request):
    main_task_id = request.GET.get('main_task_id')
    if main_task_id:
        main_task_id = int(main_task_id)

    main_task = TheMainTaskModel.objects.get(id=main_task_id)
    related_task_count = main_task.tasktyperelations_set.count()


    return JsonResponse({'data': related_task_count})

See doc about reverse relationship and .count()