简体   繁体   中英

Getting query length with Ajax / Django

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM