将PostGIS查询转换为Django QuerySet(geoDjango postgis)

时间:2018-10-09 09:19:27

标签: python django postgis geodjango

我试图弄清楚如何将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)

1 个答案:

答案 0 :(得分:0)

要使用Django的QuerySet和Django的ORM,您将需要定义models并使用它们:

# 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)