Django PostGIS 空间查询

Django PostGIS spatial query

我正在尝试在 Django 中对 PostGIS 数据库执行空间查询,但我无法执行。我已经用这个 GIS QuerySet API Reference 的原始查询试过了。我不知道我做错了什么。

这是我的 modeles.py 文件:

class RayosTotal(models.Model):
    ka = models.FloatField(db_column='kA', blank=True, null=True)  # Field name made lowercase.
    tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False)  # Field name made lowercase.
    geom = models.PointField(blank=True, null=True)

        class Meta:
            managed = False
            db_table = 'Rayos_total'
            unique_together = (('lat', 'lng', 'tiempo'),)

class Departamentos(models.Model):
    geom = models.MultiPolygonField(blank=True, null=True)
    cod_dane = models.IntegerField(db_column='COD_DANE',primary_key=True, blank=True, null=False)
    nom_dpto = models.CharField(db_column='NOM_DPTO', max_length=250, blank=True, null=True)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'departamentos'

这是我的 views.py

def join1(request):     
    points = serialize('geojson',RayosTotal.objects.all())
    x=serialize('geojson',Departamentos.objects.filter(geom__contains=points))    
    return HttpResponse(x,content_type='json')
    #with join1 I get this message: Couldn't create spatial object from lookup value

def join2(request):
    x=RayosTotal.objects.raw("""SELECT "Rayos_total".geom AS geom
FROM "public"."Rayos_total"
INNER JOIN "public"."departamentos" ON ST_Within("Rayos_total".geom, "departamentos".geom)
WHERE "departamentos"."NOM_DPTO" = 'CHOCO'""")
    return HttpResponse(x,content_type='json')
    #with join2 I get this message: Raw query must include the primary key

有什么想法吗?谢谢你的帮助

最后我在this post的帮助下解决了这个问题 这是最终代码:

from django.db import connection

def join(request):
    cursor = connection.cursor()
    cursor.execute("""SELECT "Rayos_total"."Fecha" AS geom,
        "departamentos"."NOM_DPTO" as dpto
FROM "public"."Rayos_total"
INNER JOIN "public"."departamentos" ON ST_Within("Rayos_total".geom, "departamentos".geom)
WHERE "departamentos"."COLOMBIA" = '57'
AND "Tiempo" BETWEEN NOW() - INTERVAL '1 DAYS' AND NOW()""")
    data = cursor
    return HttpResponse(data,content_type='json')

您似乎没有在查询中使用 Point 对象,因为您在查询之前序列化了数据。

这可能有效:

def join1(request):     
    # get list of points
    points = [r.geom for r in RayosTotal.objects.filter(geom__isnull=False)]
    x=serialize('geojson',Departamentos.objects.filter(geom__contains=points))    
    return HttpResponse(x,content_type='json')