如何使用来自javascript函数的值创建查询集?

mzsu5hc0  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(95)

当用户点击一个复选框时,值将被发送到一个javascript函数,该函数将获取值并异步地检查数据库中是否有任何事件,但我不知道在Django中是否有可能,我见过序列化器,但我认为它不会起作用,因为它不仅从数据库中捕捉数据,而且进行查询。有办法做到这一点吗?

requisite = requisite.objects.filter(requisite__discipline__id=33)

上面的代码将检索所需的数据,但我需要从下面的代码中获取此编号

<input class="form-check-input" type="checkbox" value="{{ discipline.id }}" id="flexCheckDefault{{ discipline.name }}" onclick="checkRequisite(this.defaultValue)">
2lpgd968

2lpgd9681#

First create a view that will receive the information from your JavaScript:

# views.py

from django.http import JsonResponse

def check_requisite(request, dis_id):
    # NOTE: I changed the class name from requisite to Requisite
    # class names should be capitalized
    requisite = Requisite.objects.filter(requisite__discipline__id=dis_id)
    if requisite:
        return JsonResponse({'answer': 'It IS in the database'})
    else:
        return JsonResponse({'answer': 'NOT in the database'})

Next, add a path to that view:

# urls.py

urlpatterns = [
    ...
    path('check_requisite/<int:dis_id>', views.check_requisite, name='check_requisite'),
    ...
]

Then, in your js file, or your you send the AJAX request:

async function check_requisite(e) {
    const check = await fetch('/check_requisite/' + e.target.value);
    const answer = await check.json();
    return answer;
}

Your checkRequisite function could call the async function above, and process the answer however you wish. Of course, the answer I'm sending in the view is just a string, but it could be more data.
The answer is incomplete, but if I had more of your code, perhaps I could come up with something more complete and specific, but I think the general idea works.

相关问题