Python 我需要关于Django程序中where条件的sql语句的帮助
这是我的节目。我需要将SQL语句中的where条件更改为使用python程序动态生成,因为有时我的where语句中的条件可能没有值。我不希望他出现在没有值的SQL语句中。在 非常感谢,我真的需要帮助,我是个新手,我想不出来Python 我需要关于Django程序中where条件的sql语句的帮助,python,mysql,django,python-3.x,Python,Mysql,Django,Python 3.x,这是我的节目。我需要将SQL语句中的where条件更改为使用python程序动态生成,因为有时我的where语句中的条件可能没有值。我不希望他出现在没有值的SQL语句中。在 非常感谢,我真的需要帮助,我是个新手,我想不出来 @csrf_exempt def test(request): if request.method == "GET": req_type = request.GET.get("get_data") if req_type:
@csrf_exempt
def test(request):
if request.method == "GET":
req_type = request.GET.get("get_data")
if req_type:
customer = request.GET.get('customer')
order_type = request.GET.get("orderType")
order_status = request.GET.get("orderStatus")
with connection.cursor() as cursor:
cursor.execute(
"SELECT account,order_id,start_at,update_at "
"FROM once WHERE user_id=%s OR %s='' AND order_id=%s OR %s='' AND status=%s OR %s='' ORDER BY order_id DESC ",
(customer, customer, order_type, order_type, order_status,order_status))
verify_list = dict_fetchall(cursor)
return HttpResponse(json.dumps(verify_list, cls=DecimalEncoder))
else:
with connection.cursor() as cursor:
cursor.execute('SELECT id,`name` FROM goods;')
goods_data = cursor.fetchall()
with connection.cursor() as cursor1:
cursor1.execute('SELECT id,account FROM `user`;')
user_data = cursor1.fetchall()
content = {"goods_data": goods_data, "user_data": user_data}
return render(request, 'user/test.html', content)
else:
return HttpResponseRedirect(reverse('users:login'))
如果我已经很好地理解了这个问题,您可以动态构造sql查询字符串,例如:
where = []
if customer:
where.append(f"user_id={customer}") # assuming customer is integer, put value without quotes
if order_type:
where.append(f"order_id={order_type}") # assuming order_type is integer, put value without quotes
if order_status:
where.append(f"status='{order_status}'") # assuming order_status is string, put value inside quotes
where = ' AND '.join(where)
where = ('WHERE ' if where else '') + where
query = f"SELECT account, order_id, start_at, update_at FROM once {where} ORDER BY order_id DESC"
with connection.cursor() as cursor:
cursor.execute(query)
在您的代码案例中,编写一个函数,将
客户、客户、订单类型、订单类型、订单状态、订单状态
作为输入,并检查输入是否为无,如果有值,则返回用户\u id=%s或%s=''和顺序\u id=%s或%s=''和状态=%s
将此输出添加到查询执行中我不想在sql where中做出判断,因为现在的数据量不允许我这样做,非常感谢您对该主题的理解。你的回答解决了我的问题。再次感谢。