I want to get a row from a postgis table given a coordinate/point. With raw sql I do it with:
SELECT * FROM parcelas
WHERE fk_area=152
AND ST_contains(geometry,ST_SetSRID(ST_Point(342884.86705619487, 6539464.45201204),32721));
The query before returns one row.
When I try to do this on django it doesn't return me any row:
from django.contrib.gis.geos import GEOSGeometry
class TestView(APIView):
def get(self, request, format=None):
pnt = GEOSGeometry('POINT(342884.86705619487 6539464.45201204)', srid=32721)
parcelas = Parcelas.objects.filter(fk_area=152,geometry__contains=pnt)
#Also tried this
#parcelas = Parcelas.objects.filter(fk_area=pk,geometry__contains='SRID=32721;POINT(342884.86705619487 6539464.45201204)')
serializer = ParcelasSerializer(parcelas, many=True)
return Response(serializer.data)
Even with django raw query it fails although in this case it returns me an internal server error (argument 3: class 'TypeError': wrong type):
class TestView(APIView):
def get(self, request, format=None):
parcelas = Parcelas.objects.raw('SELECT * FROM parcelas WHERE fk_area=152 AND ST_contains(geometry,ST_SetSRID(ST_Point(342884.86705619487, 6539464.45201204),32721))')
for p in parcelas:
#Internal server error
print(p.id)
return Response('Test')
My model parcelas look like this:
from django.contrib.gis.db import models
class Parcelas(models.Model):
id = models.BigAutoField(primary_key=True)
fk_area = models.ForeignKey(Areas, models.DO_NOTHING, db_column='fk_area')
geometry = models.GeometryField()
class Meta:
managed = False
db_table = 'parcelas'
I don't know what I'm doing wrongly if someone has any idea.
EDIT:
If I print the raw query that django made:
SELECT "parcelas"."id", "parcelas"."fk_area", "parcelas"."geometry"::bytea FROM "parcelas" WHERE ("parcelas"."fk_area" = 152 AND ST_Contains("parcelas"."geometry", ST_Transform(ST_GeomFromEWKB('\001\001\000\000 \321\177\000\000C\224\335w\223\355\024A\350\303\355\0342\362XA'::bytea), 4326)))
Seems like django is not converting it to the correct srid (32721) but I don't know why
EDIT 2:
If in my model I specify the SRID it works correctly:
class Parcelas(models.Model):
geometry = models.GeometryField(srid=32721)
The problem is that the SRID can be variable depending on the query the rows have one SRID or another so I don't want to set it to always being one.