我试图使用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)
姜戈剧本
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从数据库中获取数据。
在这种情况下,请看GeoQuerySets的'invern'函数:
https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geoquerysets/#内
作为附带说明,在视图中构造查询的方式(将参数从视图直接传递到查询中)为SQL注入攻击打开了大门,并且可能非常危险。如果您需要使用查询字符串参数的输入创建SQL,请阅读如何安全地执行此操作:https://realpython.com/prevent-python-sql-injection/#passing-safe-query-parameters