python - 如何将列表传递给 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 查询。提前感谢您的帮助!
解决方案
为什么要执行原始 SQL?代替admission_table
,编写一个具有属性 year、month、student_name、admission_date、class 的模型。然后,使用 Django 内置的 ORM 为表创建新对象。您需要做的就是遍历获取请求的月份和班级值,然后调用AdmissionTable.objects.create(<attributes here>)
.
推荐阅读
- javascript - javascript 在 then 块中提交表单并使用 swal 从非异步函数返回 false
- python-3.x - NoReverseMatch at / Reverse for 'url' with arguments '('',)' not found
- react-native - useState 没有更新状态
- angular - 比较 ngfor 变更检测的新旧值
- r - R 小数据集文本分类
- rust - 有没有办法将额外的值传递给恐慌处理程序?
- javascript - 通过客户端的浏览器从扫描仪捕获图像
- php - 加入 Find 和 Foreach 在 Laravel 中检索错误数据
- javascript - 在画布上绘制图像的裁剪版本
- php - 在目录中搜索文件并返回值