Django: Multi-parameter ORM dynamic query

There are several input boxes on the front page for searching data. The user can fill in the search criteria as needed and send it to the backend, and then the backend will query and return according to the criteria.

Finding the data found that the filter (**dict) query method can be found in the ORM query, so the following query is available.

def search_stu_info(request):
    argument = _getArguments(request)
    try:
        name = argument.get("name", "")
        class_id = argument.get("class_id", "")
        sno = argument.get("sno", "")
        kwargs = {}
        if name:
            kwargs["name__contains"] = name
        if class_id:
            kwargs["class_id"] = class_id
        if sno:
            kwargs["son"] = sno
        stu = Student.objects.filter(**kwargs)
        data = []
        for i in stu:
            data.append(model_to_dict[i])
        returnDict = {
            'count': len(data),  # 总数据量
            'data': json.dumps(data),  # 显示的数据
            'state': 200,
            'msg': "success"
        }
        return JsonResponse(returnDict, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"state": 500, "msg": "系统出错,请联系管理员", "errMsg": str(e)},json_dumps_params={'ensure_ascii': False})


def _getArguments(request):
    # 获取请求参数
    if request.method == 'GET':
        logging.error("收到GET请求")
        arguments = dict(request.GET)
        for arg in arguments:
            if type(arguments[arg]) == type([]):
                arguments[arg] = arguments[arg][0]
    else:
        logging.error("收到POST请求")
        logging.error("post-body")
        logging.error(request.body.decode())
        if "form" in request.content_type:
            arguments = request.POST
        else:
            arguments = json.loads(request.body.decode())
    return arguments

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107991407