我正在尝试在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')