I'm trying to do a spatial query in Django to a PostGIS database, but I've not been able to do it. I've try it with raw querys a with this GIS QuerySet API Reference. I dont know what I'm doing wrong.
this is my modeles.py file:
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'
and this is my 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
any ideas ? thank you for the help
At the end I solve this problem with the help of this post this is the final code:
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')