【问题标题】:How to pass a list to the SQL query in django如何将列表传递给 django 中的 SQL 查询
【发布时间】:2020-02-04 06:41:35
【问题描述】:

我正在使用下面的代码:

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 查询。 提前感谢您的帮助!

【问题讨论】:

  • 请问你为什么不用Django ORM?

标签: python sql django


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2012-09-12
    • 2018-06-16
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多