[英]How to execute PostgreSQL query in Django
I am trying to fetch the PostgreSQL table onto HTML using Django, When I execute the spatial query in the query Tool of PostgreSQL I got the perfect results, but When I'm trying to execute the same script from Django getting all rows of data. 感谢您提前提供帮助。
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 中,您可能希望使用 Django ORM 从数据库中获取数据。
在这种情况下,请查看地理查询集的“内部”function:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.