﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
12828	Invalid SQL in GIS DB	joliveirinha@…	nobody	"GIS Db generates invalid SQL when using the GIS model query as a subquery.


{{{
a = Venue.objects.filter(point__distance_lte=(Point(0, 0), Distance(m=1)))
b = Event.objects.filter(venue__in=a)
}}}


With the query set a .. all goes ok but when I use a inside b then this translates in this sql query and producing an error.


{{{
(u'SELECT ""event"".""id"", ""event"".""event_id"", ""event"".""name"", ""event"".""description"", ""event"".""site"", ""event"".""venue_id"", ""event"".""start_time"", ""event"".""end_time"", ""event"".""extra_data"" FROM ""event"" WHERE ""event"".""venue_id"" IN (SELECT U0.""id"" FROM ""venue"" U0 WHERE ST_distance_sphere(""U0"".""point"", %s) <= 1000.0)', (<django.contrib.gis.db.backend.postgis.adaptor.PostGISAdaptor object at 0x3317510>,))
}}}


The problem is that GIS ORM bind U0 to table venue but instead using that alias inside ST_distance_sphere function it uses the quoted alias, thus producing the error.

I used this code to bypass this error and it works.


{{{
b.query.where.children[0][3].data = (b.query.where.children[0][3].data[0].replace(""\""U0\"""", ""U0""), b.query.where.children[0][3].data[1:])
}}}


Note: only Venue Model use the GIS objects manager.
"		closed	GIS	1.1		fixed	invalid SQL		Design decision needed	1	0	1	0	0	0
