0

我正在尝试从数据库中搜索两个日期范围之间的记录。这是我的代码视图:

def profile(request):
    if request.method == 'POST':
        fromdate = request.POST.get('from')
        todate = request.POST.get('to')
        cursordate = connection.cursor()
        cursordate.execute('SELECT * FROM Lesson WHERE StartDateTime between "'+fromdate+'" and "'+todate+'"'
            )
        data = dictfetchall(cursordate)
        return render(request,'personal.html',{'data':data})
    else:
        cursordate = connection.cursor()
        cursordate.execute('SELECT * FROM Lesson')
        data = dictfetchall(cursordate)
        return render(request,'personal.html',{'data':data})

html:

{% for lesson in data1 %}

<div class="card mb-3 mt-1 shadow-sm">
    <div class="card-body">
        <p class="card-text">
        <div class="row">
                <div class="col-2">
                    <div>{{ lesson.StartDateTime}} - {{ lesson.EndDateTime}}</div>
                </div>
                <div class="col-4">
                    <div>{{ lesson.Name }}</div>
                </div>
        </div>
        <div class="mt-5"></div>
        </p>

    </div>
</div>
{% endfor %}

但我收到以下错误:

Invalid column name "2021-03-02". (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name "2021-03-03". (207)')

它与“StartDateTime”的类型是 DateTime 而不是 Date 的事实有关吗?但是,我尝试在 sql 查询中将日期与时间硬编码,但它仍然失败。(我知道它可以在 ORM Django 的帮助下完成,但我需要使用原始 SQL)

4

2 回答 2

0

您可以将参数作为参数传递,因此:

fromdate = request.POST.get('from')
todate = request.POST.get('to')
with connection.cursor() as cursordate:
    cursordate.execute(
        'SELECT * FROM Lesson WHERE StartDateTime BETWEEN %s AND %s;'
        [fromdate, todate]
    )

fromdate例如,如果is'2021-03-25'todateis '2021-04-13',那么我们可以过滤Lession从这些日期之间开始的 s。

然而,使用原始查询并不是一个好主意。通过在问题中使用字符串格式化查询,您会使 Web 应用程序容易受到SQL 注入[wiki]的攻击。此外,它需要手动进行各种反序列化。

通过使用 Django ORM,我们可以使用:

fromdate = request.POST.get('from')
todate = request.POST.get('to')
Lession.objects.filter(StartDateTime__range=(fromdate, todate))

由于我们在这里检索数据,而不是更改/更新/删除/创建数据,这通常是通过 GET 请求完成的,而不是 POST 请求。

于 2021-04-13T19:02:39.410 回答
0

您也可以通过 ORM 实现上述查询,它写为

Lesson.objects.filter(StartDateTime__gte=fromdate, StartDateTime__lt=to_date)
于 2021-04-13T18:53:59.167 回答