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 :
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 :
See doc about reverse relationship and .count()