首页 > 解决方案 > 如何将列表传递给 django 中的 SQL 查询

问题描述

我正在使用下面的代码:

def internal(request):

try:
    year=''
    month=[]
    class=[]
    results=[]
    conn = connections["connection1"]
    cursor = conn.cursor()
    year = request.GET.get('year')
    print(year)
    month = request.GET.getlist('month[]')
    for i in month:
        print("Months::"+i)
    class = request.GET.getlist('class[]')
    response_list = []
    cursor.execute(" select Year,month,student_name,admission_date,class from admission_table\
    where MONTH(admission_date) in ('"+(month)+"') AND YEAR(admission_date) in ('"+year+"') AND class in ('"+class+"') ")

    rows = cursor.fetchall()
    print(rows)
    if rows:
        for row in rows:
            response_list.append({'year':row[0],'month':row[1],'student_name':row[2],'admission_date':str(row[3]),'class':row[4]})
except Exception as e:
    print(str(e))

return HttpResponse(json.dumps(response_list))

如何将列表中的月份和类值传递给 SQL 查询。提前感谢您的帮助!

标签: pythonsqldjango

解决方案


为什么要执行原始 SQL?代替admission_table,编写一个具有属性 year、month、student_name、admission_date、class 的模型。然后,使用 Django 内置的 ORM 为表创建新对象。您需要做的就是遍历获取请求的月份和班级值,然后调用AdmissionTable.objects.create(<attributes here>).


推荐阅读