【问题标题】:How to search by the date?如何按日期搜索?
【发布时间】:2021-04-13 18:48:58
【问题描述】:

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

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)

【问题讨论】:

  • 你这里可以使用SQL注入...

标签: sql django rawsql


【解决方案1】:

上面的查询也可以通过ORM实现,写成

Lesson.objects.filter(StartDateTime__gte=fromdate, StartDateTime__lt=to_date)

【讨论】:

    【解决方案2】:

    你可以将参数作为参数传递,所以:

    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 是例如'2021-03-25'todate'2021-04-13',那么我们可以过滤出在这些日期之间开始的Lessions。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多