[英]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.根据表单中的选择,我想获取与所选数据的id相匹配的记录数作为整数。
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:这是我的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.我想在表单中写入与所选数据的main_task_id
关联的关系任务数。 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() 数数()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.