def qiye_group(request, columnName): if request.method in ["POST", "GET"]: msg = {"code": normal_code, "msg": "成功", "data": {}} where = ' where 1 = 1 ' sql = "SELECT COUNT(*) AS total, " + columnName + " FROM qiye " + where + " GROUP BY " + columnName + " LIMIT 10" L = [] cursor = connection.cursor() cursor.execute(sql) desc = cursor.description data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] for online_dict in data_dict: for key in online_dict: if 'datetime.datetime' in str(type(online_dict[key])): online_dict[key] = online_dict[key].strftime("%Y-%m-%d") else: pass L.append(online_dict) msg['data'] = L return JsonResponse(msg)
时间: 2024-01-29 07:02:08 浏览: 129
这段代码是一个Django视图函数,用于查询数据库表qiye中指定列columnName的分组数据,并以JSON格式返回前端。视图函数首先判断请求方法是否为POST或GET,然后定义了一个返回给前端的JSON数据msg,其中包括code、msg和data三个字段。接下来构造SQL语句,使用COUNT和GROUP BY语句对qiye表中指定列进行分组统计,并限制查询结果返回前10条数据。然后利用cursor执行SQL语句查询数据,并对查询结果进行处理,将datetime类型的数据转换为字符串类型,最后将处理后的数据存入L列表中,作为msg的data字段返回给前端。
阅读全文