python - 将 PostGIS 查询转换为 Django QuerySet (geoDjango postgis)
问题描述
我想弄清楚如何将 PostGIS 查询转换为 GeoDjango:
def my_view(request, tempounix):
conn.execute('SELECT ST_X(geom) as x, ST_Y(geom) AS y, accuracy, altitude, speed, tempounix '
'FROM authapp_posizione '
'ORDER BY tempounix DESC LIMIT 1;')
x, y, accuracy, altitude, speed, timestamp = c.fetchone()
data = {
"geometry": {
"type": "Point",
"coordinates": [x, y],
},
"type": "Feature",
"properties": {
"accuracy": accuracy,
"altitude": altitude,
"speed": speed,
"tempounix": tempounix,
},
}
return JsonResponse(data)
解决方案
要使用 Django 的 QuerySets 和 Django 的 ORM,您需要定义模型并使用它们:
# models.py:
class Position(models.Model):
geom = models.PointField(...)
accuracy = models.IntegerField()
altitude = models.IntegerField()
speed = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
现在:
p = Position.objects.order_by("-created_at").first()
if p:
print(p.created_at, p.geom.coordinates, p.altitude)
推荐阅读
- javascript - 有没有办法在浏览器扩展开始加载之前运行 JavaScript?
- c++ - 编译时无法识别树类中的结构节点
- vagrant - 流浪者重新加载丢失的同步文件夹
- hawtio - Hawtio 会从 AngularJS 迁移出去吗?
- c - 强化工具缓冲区溢出
- javascript - 点击菜单按钮后 ul 消失了
- postgresql - Apache 上的 Flask 应用程序通过 Sqlalchemy 访问 Postgres
- javascript - 检查数组是否具有特定长度的元素
- numpy - AWS EMR:Zeppelin 从 python 2.7 获取 numpy 版本而不是更高版本
- node.js - 外键茉莉花测试失败