【问题标题】:How to execute PostgreSQL query in Django如何在 Django 中执行 PostgreSQL 查询
【发布时间】:2021-06-14 21:09:09
【问题描述】:

我正在尝试使用 Django 将 PostgreSQL 表提取到 HTML 中,当我在 PostgreSQL 的查询工具中执行空间查询时,我得到了完美的结果,但是当我尝试从 Django 执行相同的脚本时,得到所有行数据的。感谢您提前提供帮助。

SQL query which is working perfectly

SELECT *
    FROM jhk_schls as point,jhk_urban as polygon
WHERE ST_Within(point.geom, polygon.geom)

Django 脚本

def search(request):
    if request.method == "POST":
        first_layer = request.POST.get('first_layer')
        spati_func = request.POST.get('spa_func')
        second_layer = request.POST.get('secon_layer')
        within_fun = 'select * from' + " " + str(first_layer) + " " + 'as point,' + str(second_layer) + " " + 'as polygon' + " " + 'WHERE' + " " + str(spati_func)+'(point.geom, polygon.geom)'
        cursor = connection.cursor()
        cursor.execute(within_fun)
        data = cursor.fetchall()
        return render(request, 'geoit/search.html',{ 'data':data})
    return render(request,'geoit/search.html')

HTML

<span>Select Layer</span>
      <select name="first_layer">
     <option value="-1" disabled  selected >Please select</option>
     Layer<li><option value="jhk_schls">jhk_schls</option></li>
    </select>
  </br>
  <span>Spatial Functions</span>
<select name="spa_func">
     <option value="-1" disabled  selected >Please select</option>
     Layer<li><option value="ST_Within">ST_Within</option></li>
    </select>
</br>
<span>Select Layer</span>
<select name="secon_layer">

     <option value="-1" disabled  selected >Please select</option>
     Layer<li><option value="jhk_urban">jhk_urban</option></li>
     
    </select>
<input type="submit" value="submit">
          </p>
        </div>
</form>
            <button type="submit" value="submit"><i class="fa fa-search"></i>
            </button>
        </form>
        <p></p>
        <center>
            <table>
    
           
        {% for item in data %}
                  <tr>
                <td>{{ item.0 }}</td>
                <td>{{ item.2 }}</td>
                 
            </tr>
        {% endfor %}
    </table>
        </center>
```

【问题讨论】:

  • 两件非常重要的事情:在 Django 中,您不使用 SQL,而是使用 ORM,如果在其他情况下必须使用 SQL,则永远不要使用字符串连接来构造它。这将导致 SQL 注入漏洞。你拿了Djangotutorials吗?
  • 能否提供解决问题的教程?否则,提供任何类似的项目。我是 Django 的中级。

标签: python html django postgresql postgis


【解决方案1】:

在 Django 中,您可能希望使用 Django ORM 从数据库中获取数据。

在这种情况下,请查看 geoquerysets 的 'within' 函数:

https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geoquerysets/#within

附带说明一下,您在视图中构造查询的方式,将视图中的参数直接传递到查询中,会为您带来 SQL 注入攻击,并且可能非常危险。 如果您需要使用查询字符串参数的输入创建 SQL,请阅读如何安全地执行此操作:https://realpython.com/prevent-python-sql-injection/#passing-safe-query-parameters

【讨论】:

    猜你喜欢
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多