query.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. from django.db import connections
  2. from django.db.models.query import QuerySet, ValuesQuerySet, ValuesListQuerySet
  3. from django.contrib.gis import memoryview
  4. from django.contrib.gis.db.models import aggregates
  5. from django.contrib.gis.db.models.fields import get_srid_info, PointField, LineStringField
  6. from django.contrib.gis.db.models.sql import AreaField, DistanceField, GeomField, GeoQuery
  7. from django.contrib.gis.geometry.backend import Geometry
  8. from django.contrib.gis.measure import Area, Distance
  9. from django.utils import six
  10. class GeoQuerySet(QuerySet):
  11. "The Geographic QuerySet."
  12. ### Methods overloaded from QuerySet ###
  13. def __init__(self, model=None, query=None, using=None, hints=None):
  14. super(GeoQuerySet, self).__init__(model=model, query=query, using=using, hints=hints)
  15. self.query = query or GeoQuery(self.model)
  16. def values(self, *fields):
  17. return self._clone(klass=GeoValuesQuerySet, setup=True, _fields=fields)
  18. def values_list(self, *fields, **kwargs):
  19. flat = kwargs.pop('flat', False)
  20. if kwargs:
  21. raise TypeError('Unexpected keyword arguments to values_list: %s'
  22. % (list(kwargs),))
  23. if flat and len(fields) > 1:
  24. raise TypeError("'flat' is not valid when values_list is called with more than one field.")
  25. return self._clone(klass=GeoValuesListQuerySet, setup=True, flat=flat,
  26. _fields=fields)
  27. ### GeoQuerySet Methods ###
  28. def area(self, tolerance=0.05, **kwargs):
  29. """
  30. Returns the area of the geographic field in an `area` attribute on
  31. each element of this GeoQuerySet.
  32. """
  33. # Performing setup here rather than in `_spatial_attribute` so that
  34. # we can get the units for `AreaField`.
  35. procedure_args, geo_field = self._spatial_setup('area', field_name=kwargs.get('field_name', None))
  36. s = {'procedure_args': procedure_args,
  37. 'geo_field': geo_field,
  38. 'setup': False,
  39. }
  40. connection = connections[self.db]
  41. backend = connection.ops
  42. if backend.oracle:
  43. s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
  44. s['procedure_args']['tolerance'] = tolerance
  45. s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters.
  46. elif backend.postgis or backend.spatialite:
  47. if backend.geography:
  48. # Geography fields support area calculation, returns square meters.
  49. s['select_field'] = AreaField('sq_m')
  50. elif not geo_field.geodetic(connection):
  51. # Getting the area units of the geographic field.
  52. s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection)))
  53. else:
  54. # TODO: Do we want to support raw number areas for geodetic fields?
  55. raise Exception('Area on geodetic coordinate systems not supported.')
  56. return self._spatial_attribute('area', s, **kwargs)
  57. def centroid(self, **kwargs):
  58. """
  59. Returns the centroid of the geographic field in a `centroid`
  60. attribute on each element of this GeoQuerySet.
  61. """
  62. return self._geom_attribute('centroid', **kwargs)
  63. def collect(self, **kwargs):
  64. """
  65. Performs an aggregate collect operation on the given geometry field.
  66. This is analogous to a union operation, but much faster because
  67. boundaries are not dissolved.
  68. """
  69. return self._spatial_aggregate(aggregates.Collect, **kwargs)
  70. def difference(self, geom, **kwargs):
  71. """
  72. Returns the spatial difference of the geographic field in a `difference`
  73. attribute on each element of this GeoQuerySet.
  74. """
  75. return self._geomset_attribute('difference', geom, **kwargs)
  76. def distance(self, geom, **kwargs):
  77. """
  78. Returns the distance from the given geographic field name to the
  79. given geometry in a `distance` attribute on each element of the
  80. GeoQuerySet.
  81. Keyword Arguments:
  82. `spheroid` => If the geometry field is geodetic and PostGIS is
  83. the spatial database, then the more accurate
  84. spheroid calculation will be used instead of the
  85. quicker sphere calculation.
  86. `tolerance` => Used only for Oracle. The tolerance is
  87. in meters -- a default of 5 centimeters (0.05)
  88. is used.
  89. """
  90. return self._distance_attribute('distance', geom, **kwargs)
  91. def envelope(self, **kwargs):
  92. """
  93. Returns a Geometry representing the bounding box of the
  94. Geometry field in an `envelope` attribute on each element of
  95. the GeoQuerySet.
  96. """
  97. return self._geom_attribute('envelope', **kwargs)
  98. def extent(self, **kwargs):
  99. """
  100. Returns the extent (aggregate) of the features in the GeoQuerySet. The
  101. extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
  102. """
  103. return self._spatial_aggregate(aggregates.Extent, **kwargs)
  104. def extent3d(self, **kwargs):
  105. """
  106. Returns the aggregate extent, in 3D, of the features in the
  107. GeoQuerySet. It is returned as a 6-tuple, comprising:
  108. (xmin, ymin, zmin, xmax, ymax, zmax).
  109. """
  110. return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
  111. def force_rhr(self, **kwargs):
  112. """
  113. Returns a modified version of the Polygon/MultiPolygon in which
  114. all of the vertices follow the Right-Hand-Rule. By default,
  115. this is attached as the `force_rhr` attribute on each element
  116. of the GeoQuerySet.
  117. """
  118. return self._geom_attribute('force_rhr', **kwargs)
  119. def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
  120. """
  121. Returns a GeoJSON representation of the geometry field in a `geojson`
  122. attribute on each element of the GeoQuerySet.
  123. The `crs` and `bbox` keywords may be set to True if the user wants
  124. the coordinate reference system and the bounding box to be included
  125. in the GeoJSON representation of the geometry.
  126. """
  127. backend = connections[self.db].ops
  128. if not backend.geojson:
  129. raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ '
  130. 'support GeoJSON serialization.')
  131. if not isinstance(precision, six.integer_types):
  132. raise TypeError('Precision keyword must be set with an integer.')
  133. # Setting the options flag -- which depends on which version of
  134. # PostGIS we're using. SpatiaLite only uses the first group of options.
  135. if backend.spatial_version >= (1, 4, 0):
  136. options = 0
  137. if crs and bbox:
  138. options = 3
  139. elif bbox:
  140. options = 1
  141. elif crs:
  142. options = 2
  143. else:
  144. options = 0
  145. if crs and bbox:
  146. options = 3
  147. elif crs:
  148. options = 1
  149. elif bbox:
  150. options = 2
  151. s = {'desc': 'GeoJSON',
  152. 'procedure_args': {'precision': precision, 'options': options},
  153. 'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s',
  154. }
  155. return self._spatial_attribute('geojson', s, **kwargs)
  156. def geohash(self, precision=20, **kwargs):
  157. """
  158. Returns a GeoHash representation of the given field in a `geohash`
  159. attribute on each element of the GeoQuerySet.
  160. The `precision` keyword may be used to custom the number of
  161. _characters_ used in the output GeoHash, the default is 20.
  162. """
  163. s = {'desc': 'GeoHash',
  164. 'procedure_args': {'precision': precision},
  165. 'procedure_fmt': '%(geo_col)s,%(precision)s',
  166. }
  167. return self._spatial_attribute('geohash', s, **kwargs)
  168. def gml(self, precision=8, version=2, **kwargs):
  169. """
  170. Returns GML representation of the given field in a `gml` attribute
  171. on each element of the GeoQuerySet.
  172. """
  173. backend = connections[self.db].ops
  174. s = {'desc': 'GML', 'procedure_args': {'precision': precision}}
  175. if backend.postgis:
  176. # PostGIS AsGML() aggregate function parameter order depends on the
  177. # version -- uggh.
  178. if backend.spatial_version > (1, 3, 1):
  179. s['procedure_fmt'] = '%(version)s,%(geo_col)s,%(precision)s'
  180. else:
  181. s['procedure_fmt'] = '%(geo_col)s,%(precision)s,%(version)s'
  182. s['procedure_args'] = {'precision': precision, 'version': version}
  183. return self._spatial_attribute('gml', s, **kwargs)
  184. def intersection(self, geom, **kwargs):
  185. """
  186. Returns the spatial intersection of the Geometry field in
  187. an `intersection` attribute on each element of this
  188. GeoQuerySet.
  189. """
  190. return self._geomset_attribute('intersection', geom, **kwargs)
  191. def kml(self, **kwargs):
  192. """
  193. Returns KML representation of the geometry field in a `kml`
  194. attribute on each element of this GeoQuerySet.
  195. """
  196. s = {'desc': 'KML',
  197. 'procedure_fmt': '%(geo_col)s,%(precision)s',
  198. 'procedure_args': {'precision': kwargs.pop('precision', 8)},
  199. }
  200. return self._spatial_attribute('kml', s, **kwargs)
  201. def length(self, **kwargs):
  202. """
  203. Returns the length of the geometry field as a `Distance` object
  204. stored in a `length` attribute on each element of this GeoQuerySet.
  205. """
  206. return self._distance_attribute('length', None, **kwargs)
  207. def make_line(self, **kwargs):
  208. """
  209. Creates a linestring from all of the PointField geometries in the
  210. this GeoQuerySet and returns it. This is a spatial aggregate
  211. method, and thus returns a geometry rather than a GeoQuerySet.
  212. """
  213. return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs)
  214. def mem_size(self, **kwargs):
  215. """
  216. Returns the memory size (number of bytes) that the geometry field takes
  217. in a `mem_size` attribute on each element of this GeoQuerySet.
  218. """
  219. return self._spatial_attribute('mem_size', {}, **kwargs)
  220. def num_geom(self, **kwargs):
  221. """
  222. Returns the number of geometries if the field is a
  223. GeometryCollection or Multi* Field in a `num_geom`
  224. attribute on each element of this GeoQuerySet; otherwise
  225. the sets with None.
  226. """
  227. return self._spatial_attribute('num_geom', {}, **kwargs)
  228. def num_points(self, **kwargs):
  229. """
  230. Returns the number of points in the first linestring in the
  231. Geometry field in a `num_points` attribute on each element of
  232. this GeoQuerySet; otherwise sets with None.
  233. """
  234. return self._spatial_attribute('num_points', {}, **kwargs)
  235. def perimeter(self, **kwargs):
  236. """
  237. Returns the perimeter of the geometry field as a `Distance` object
  238. stored in a `perimeter` attribute on each element of this GeoQuerySet.
  239. """
  240. return self._distance_attribute('perimeter', None, **kwargs)
  241. def point_on_surface(self, **kwargs):
  242. """
  243. Returns a Point geometry guaranteed to lie on the surface of the
  244. Geometry field in a `point_on_surface` attribute on each element
  245. of this GeoQuerySet; otherwise sets with None.
  246. """
  247. return self._geom_attribute('point_on_surface', **kwargs)
  248. def reverse_geom(self, **kwargs):
  249. """
  250. Reverses the coordinate order of the geometry, and attaches as a
  251. `reverse` attribute on each element of this GeoQuerySet.
  252. """
  253. s = {'select_field': GeomField()}
  254. kwargs.setdefault('model_att', 'reverse_geom')
  255. if connections[self.db].ops.oracle:
  256. s['geo_field_type'] = LineStringField
  257. return self._spatial_attribute('reverse', s, **kwargs)
  258. def scale(self, x, y, z=0.0, **kwargs):
  259. """
  260. Scales the geometry to a new size by multiplying the ordinates
  261. with the given x,y,z scale factors.
  262. """
  263. if connections[self.db].ops.spatialite:
  264. if z != 0.0:
  265. raise NotImplementedError('SpatiaLite does not support 3D scaling.')
  266. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
  267. 'procedure_args': {'x': x, 'y': y},
  268. 'select_field': GeomField(),
  269. }
  270. else:
  271. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
  272. 'procedure_args': {'x': x, 'y': y, 'z': z},
  273. 'select_field': GeomField(),
  274. }
  275. return self._spatial_attribute('scale', s, **kwargs)
  276. def snap_to_grid(self, *args, **kwargs):
  277. """
  278. Snap all points of the input geometry to the grid. How the
  279. geometry is snapped to the grid depends on how many arguments
  280. were given:
  281. - 1 argument : A single size to snap both the X and Y grids to.
  282. - 2 arguments: X and Y sizes to snap the grid to.
  283. - 4 arguments: X, Y sizes and the X, Y origins.
  284. """
  285. if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]:
  286. raise TypeError('Size argument(s) for the grid must be a float or integer values.')
  287. nargs = len(args)
  288. if nargs == 1:
  289. size = args[0]
  290. procedure_fmt = '%(geo_col)s,%(size)s'
  291. procedure_args = {'size': size}
  292. elif nargs == 2:
  293. xsize, ysize = args
  294. procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s'
  295. procedure_args = {'xsize': xsize, 'ysize': ysize}
  296. elif nargs == 4:
  297. xsize, ysize, xorigin, yorigin = args
  298. procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s'
  299. procedure_args = {'xsize': xsize, 'ysize': ysize,
  300. 'xorigin': xorigin, 'yorigin': yorigin}
  301. else:
  302. raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.')
  303. s = {'procedure_fmt': procedure_fmt,
  304. 'procedure_args': procedure_args,
  305. 'select_field': GeomField(),
  306. }
  307. return self._spatial_attribute('snap_to_grid', s, **kwargs)
  308. def svg(self, relative=False, precision=8, **kwargs):
  309. """
  310. Returns SVG representation of the geographic field in a `svg`
  311. attribute on each element of this GeoQuerySet.
  312. Keyword Arguments:
  313. `relative` => If set to True, this will evaluate the path in
  314. terms of relative moves (rather than absolute).
  315. `precision` => May be used to set the maximum number of decimal
  316. digits used in output (defaults to 8).
  317. """
  318. relative = int(bool(relative))
  319. if not isinstance(precision, six.integer_types):
  320. raise TypeError('SVG precision keyword argument must be an integer.')
  321. s = {
  322. 'desc': 'SVG',
  323. 'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s',
  324. 'procedure_args': {
  325. 'rel': relative,
  326. 'precision': precision,
  327. }
  328. }
  329. return self._spatial_attribute('svg', s, **kwargs)
  330. def sym_difference(self, geom, **kwargs):
  331. """
  332. Returns the symmetric difference of the geographic field in a
  333. `sym_difference` attribute on each element of this GeoQuerySet.
  334. """
  335. return self._geomset_attribute('sym_difference', geom, **kwargs)
  336. def translate(self, x, y, z=0.0, **kwargs):
  337. """
  338. Translates the geometry to a new location using the given numeric
  339. parameters as offsets.
  340. """
  341. if connections[self.db].ops.spatialite:
  342. if z != 0.0:
  343. raise NotImplementedError('SpatiaLite does not support 3D translation.')
  344. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
  345. 'procedure_args': {'x': x, 'y': y},
  346. 'select_field': GeomField(),
  347. }
  348. else:
  349. s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
  350. 'procedure_args': {'x': x, 'y': y, 'z': z},
  351. 'select_field': GeomField(),
  352. }
  353. return self._spatial_attribute('translate', s, **kwargs)
  354. def transform(self, srid=4326, **kwargs):
  355. """
  356. Transforms the given geometry field to the given SRID. If no SRID is
  357. provided, the transformation will default to using 4326 (WGS84).
  358. """
  359. if not isinstance(srid, six.integer_types):
  360. raise TypeError('An integer SRID must be provided.')
  361. field_name = kwargs.get('field_name', None)
  362. tmp, geo_field = self._spatial_setup('transform', field_name=field_name)
  363. # Getting the selection SQL for the given geographic field.
  364. field_col = self._geocol_select(geo_field, field_name)
  365. # Why cascading substitutions? Because spatial backends like
  366. # Oracle and MySQL already require a function call to convert to text, thus
  367. # when there's also a transformation we need to cascade the substitutions.
  368. # For example, 'SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM( ... )'
  369. geo_col = self.query.custom_select.get(geo_field, field_col)
  370. # Setting the key for the field's column with the custom SELECT SQL to
  371. # override the geometry column returned from the database.
  372. custom_sel = '%s(%s, %s)' % (connections[self.db].ops.transform, geo_col, srid)
  373. # TODO: Should we have this as an alias?
  374. # custom_sel = '(%s(%s, %s)) AS %s' % (SpatialBackend.transform, geo_col, srid, qn(geo_field.name))
  375. self.query.transformed_srid = srid # So other GeoQuerySet methods
  376. self.query.custom_select[geo_field] = custom_sel
  377. return self._clone()
  378. def union(self, geom, **kwargs):
  379. """
  380. Returns the union of the geographic field with the given
  381. Geometry in a `union` attribute on each element of this GeoQuerySet.
  382. """
  383. return self._geomset_attribute('union', geom, **kwargs)
  384. def unionagg(self, **kwargs):
  385. """
  386. Performs an aggregate union on the given geometry field. Returns
  387. None if the GeoQuerySet is empty. The `tolerance` keyword is for
  388. Oracle backends only.
  389. """
  390. return self._spatial_aggregate(aggregates.Union, **kwargs)
  391. ### Private API -- Abstracted DRY routines. ###
  392. def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None):
  393. """
  394. Performs set up for executing the spatial function.
  395. """
  396. # Does the spatial backend support this?
  397. connection = connections[self.db]
  398. func = getattr(connection.ops, att, False)
  399. if desc is None:
  400. desc = att
  401. if not func:
  402. raise NotImplementedError('%s stored procedure not available on '
  403. 'the %s backend.' %
  404. (desc, connection.ops.name))
  405. # Initializing the procedure arguments.
  406. procedure_args = {'function': func}
  407. # Is there a geographic field in the model to perform this
  408. # operation on?
  409. geo_field = self.query._geo_field(field_name)
  410. if not geo_field:
  411. raise TypeError('%s output only available on GeometryFields.' % func)
  412. # If the `geo_field_type` keyword was used, then enforce that
  413. # type limitation.
  414. if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
  415. raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))
  416. # Setting the procedure args.
  417. procedure_args['geo_col'] = self._geocol_select(geo_field, field_name)
  418. return procedure_args, geo_field
  419. def _spatial_aggregate(self, aggregate, field_name=None,
  420. geo_field_type=None, tolerance=0.05):
  421. """
  422. DRY routine for calling aggregate spatial stored procedures and
  423. returning their result to the caller of the function.
  424. """
  425. # Getting the field the geographic aggregate will be called on.
  426. geo_field = self.query._geo_field(field_name)
  427. if not geo_field:
  428. raise TypeError('%s aggregate only available on GeometryFields.' % aggregate.name)
  429. # Checking if there are any geo field type limitations on this
  430. # aggregate (e.g. ST_Makeline only operates on PointFields).
  431. if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
  432. raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__))
  433. # Getting the string expression of the field name, as this is the
  434. # argument taken by `Aggregate` objects.
  435. agg_col = field_name or geo_field.name
  436. # Adding any keyword parameters for the Aggregate object. Oracle backends
  437. # in particular need an additional `tolerance` parameter.
  438. agg_kwargs = {}
  439. if connections[self.db].ops.oracle:
  440. agg_kwargs['tolerance'] = tolerance
  441. # Calling the QuerySet.aggregate, and returning only the value of the aggregate.
  442. return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg']
  443. def _spatial_attribute(self, att, settings, field_name=None, model_att=None):
  444. """
  445. DRY routine for calling a spatial stored procedure on a geometry column
  446. and attaching its output as an attribute of the model.
  447. Arguments:
  448. att:
  449. The name of the spatial attribute that holds the spatial
  450. SQL function to call.
  451. settings:
  452. Dictonary of internal settings to customize for the spatial procedure.
  453. Public Keyword Arguments:
  454. field_name:
  455. The name of the geographic field to call the spatial
  456. function on. May also be a lookup to a geometry field
  457. as part of a foreign key relation.
  458. model_att:
  459. The name of the model attribute to attach the output of
  460. the spatial function to.
  461. """
  462. # Default settings.
  463. settings.setdefault('desc', None)
  464. settings.setdefault('geom_args', ())
  465. settings.setdefault('geom_field', None)
  466. settings.setdefault('procedure_args', {})
  467. settings.setdefault('procedure_fmt', '%(geo_col)s')
  468. settings.setdefault('select_params', [])
  469. connection = connections[self.db]
  470. backend = connection.ops
  471. # Performing setup for the spatial column, unless told not to.
  472. if settings.get('setup', True):
  473. default_args, geo_field = self._spatial_setup(att, desc=settings['desc'], field_name=field_name,
  474. geo_field_type=settings.get('geo_field_type', None))
  475. for k, v in six.iteritems(default_args):
  476. settings['procedure_args'].setdefault(k, v)
  477. else:
  478. geo_field = settings['geo_field']
  479. # The attribute to attach to the model.
  480. if not isinstance(model_att, six.string_types):
  481. model_att = att
  482. # Special handling for any argument that is a geometry.
  483. for name in settings['geom_args']:
  484. # Using the field's get_placeholder() routine to get any needed
  485. # transformation SQL.
  486. geom = geo_field.get_prep_value(settings['procedure_args'][name])
  487. params = geo_field.get_db_prep_lookup('contains', geom, connection=connection)
  488. geom_placeholder = geo_field.get_placeholder(geom, connection)
  489. # Replacing the procedure format with that of any needed
  490. # transformation SQL.
  491. old_fmt = '%%(%s)s' % name
  492. new_fmt = geom_placeholder % '%%s'
  493. settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt)
  494. settings['select_params'].extend(params)
  495. # Getting the format for the stored procedure.
  496. fmt = '%%(function)s(%s)' % settings['procedure_fmt']
  497. # If the result of this function needs to be converted.
  498. if settings.get('select_field', False):
  499. sel_fld = settings['select_field']
  500. if isinstance(sel_fld, GeomField) and backend.select:
  501. self.query.custom_select[model_att] = backend.select
  502. if connection.ops.oracle:
  503. sel_fld.empty_strings_allowed = False
  504. self.query.extra_select_fields[model_att] = sel_fld
  505. # Finally, setting the extra selection attribute with
  506. # the format string expanded with the stored procedure
  507. # arguments.
  508. return self.extra(select={model_att: fmt % settings['procedure_args']},
  509. select_params=settings['select_params'])
  510. def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
  511. """
  512. DRY routine for GeoQuerySet distance attribute routines.
  513. """
  514. # Setting up the distance procedure arguments.
  515. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None))
  516. # If geodetic defaulting distance attribute to meters (Oracle and
  517. # PostGIS spherical distances return meters). Otherwise, use the
  518. # units of the geometry field.
  519. connection = connections[self.db]
  520. geodetic = geo_field.geodetic(connection)
  521. geography = geo_field.geography
  522. if geodetic:
  523. dist_att = 'm'
  524. else:
  525. dist_att = Distance.unit_attname(geo_field.units_name(connection))
  526. # Shortcut booleans for what distance function we're using and
  527. # whether the geometry field is 3D.
  528. distance = func == 'distance'
  529. length = func == 'length'
  530. perimeter = func == 'perimeter'
  531. if not (distance or length or perimeter):
  532. raise ValueError('Unknown distance function: %s' % func)
  533. geom_3d = geo_field.dim == 3
  534. # The field's get_db_prep_lookup() is used to get any
  535. # extra distance parameters. Here we set up the
  536. # parameters that will be passed in to field's function.
  537. lookup_params = [geom or 'POINT (0 0)', 0]
  538. # Getting the spatial backend operations.
  539. backend = connection.ops
  540. # If the spheroid calculation is desired, either by the `spheroid`
  541. # keyword or when calculating the length of geodetic field, make
  542. # sure the 'spheroid' distance setting string is passed in so we
  543. # get the correct spatial stored procedure.
  544. if spheroid or (backend.postgis and geodetic and
  545. (not geography) and length):
  546. lookup_params.append('spheroid')
  547. lookup_params = geo_field.get_prep_value(lookup_params)
  548. params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection)
  549. # The `geom_args` flag is set to true if a geometry parameter was
  550. # passed in.
  551. geom_args = bool(geom)
  552. if backend.oracle:
  553. if distance:
  554. procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s'
  555. elif length or perimeter:
  556. procedure_fmt = '%(geo_col)s,%(tolerance)s'
  557. procedure_args['tolerance'] = tolerance
  558. else:
  559. # Getting whether this field is in units of degrees since the field may have
  560. # been transformed via the `transform` GeoQuerySet method.
  561. if self.query.transformed_srid:
  562. u, unit_name, s = get_srid_info(self.query.transformed_srid, connection)
  563. geodetic = unit_name.lower() in geo_field.geodetic_units
  564. if backend.spatialite and geodetic:
  565. raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.')
  566. if distance:
  567. if self.query.transformed_srid:
  568. # Setting the `geom_args` flag to false because we want to handle
  569. # transformation SQL here, rather than the way done by default
  570. # (which will transform to the original SRID of the field rather
  571. # than to what was transformed to).
  572. geom_args = False
  573. procedure_fmt = '%s(%%(geo_col)s, %s)' % (backend.transform, self.query.transformed_srid)
  574. if geom.srid is None or geom.srid == self.query.transformed_srid:
  575. # If the geom parameter srid is None, it is assumed the coordinates
  576. # are in the transformed units. A placeholder is used for the
  577. # geometry parameter. `GeomFromText` constructor is also needed
  578. # to wrap geom placeholder for SpatiaLite.
  579. if backend.spatialite:
  580. procedure_fmt += ', %s(%%%%s, %s)' % (backend.from_text, self.query.transformed_srid)
  581. else:
  582. procedure_fmt += ', %%s'
  583. else:
  584. # We need to transform the geom to the srid specified in `transform()`,
  585. # so wrapping the geometry placeholder in transformation SQL.
  586. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText`
  587. # constructor.
  588. if backend.spatialite:
  589. procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (backend.transform, backend.from_text,
  590. geom.srid, self.query.transformed_srid)
  591. else:
  592. procedure_fmt += ', %s(%%%%s, %s)' % (backend.transform, self.query.transformed_srid)
  593. else:
  594. # `transform()` was not used on this GeoQuerySet.
  595. procedure_fmt = '%(geo_col)s,%(geom)s'
  596. if not geography and geodetic:
  597. # Spherical distance calculation is needed (because the geographic
  598. # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid()
  599. # procedures may only do queries from point columns to point geometries
  600. # some error checking is required.
  601. if not backend.geography:
  602. if not isinstance(geo_field, PointField):
  603. raise ValueError('Spherical distance calculation only supported on PointFields.')
  604. if not str(Geometry(memoryview(params[0].ewkb)).geom_type) == 'Point':
  605. raise ValueError('Spherical distance calculation only supported with Point Geometry parameters')
  606. # The `function` procedure argument needs to be set differently for
  607. # geodetic distance calculations.
  608. if spheroid:
  609. # Call to distance_spheroid() requires spheroid param as well.
  610. procedure_fmt += ",'%(spheroid)s'"
  611. procedure_args.update({'function': backend.distance_spheroid, 'spheroid': params[1]})
  612. else:
  613. procedure_args.update({'function': backend.distance_sphere})
  614. elif length or perimeter:
  615. procedure_fmt = '%(geo_col)s'
  616. if not geography and geodetic and length:
  617. # There's no `length_sphere`, and `length_spheroid` also
  618. # works on 3D geometries.
  619. procedure_fmt += ",'%(spheroid)s'"
  620. procedure_args.update({'function': backend.length_spheroid, 'spheroid': params[1]})
  621. elif geom_3d and backend.postgis:
  622. # Use 3D variants of perimeter and length routines on PostGIS.
  623. if perimeter:
  624. procedure_args.update({'function': backend.perimeter3d})
  625. elif length:
  626. procedure_args.update({'function': backend.length3d})
  627. # Setting up the settings for `_spatial_attribute`.
  628. s = {'select_field': DistanceField(dist_att),
  629. 'setup': False,
  630. 'geo_field': geo_field,
  631. 'procedure_args': procedure_args,
  632. 'procedure_fmt': procedure_fmt,
  633. }
  634. if geom_args:
  635. s['geom_args'] = ('geom',)
  636. s['procedure_args']['geom'] = geom
  637. elif geom:
  638. # The geometry is passed in as a parameter because we handled
  639. # transformation conditions in this routine.
  640. s['select_params'] = [backend.Adapter(geom)]
  641. return self._spatial_attribute(func, s, **kwargs)
  642. def _geom_attribute(self, func, tolerance=0.05, **kwargs):
  643. """
  644. DRY routine for setting up a GeoQuerySet method that attaches a
  645. Geometry attribute (e.g., `centroid`, `point_on_surface`).
  646. """
  647. s = {'select_field': GeomField()}
  648. if connections[self.db].ops.oracle:
  649. s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
  650. s['procedure_args'] = {'tolerance': tolerance}
  651. return self._spatial_attribute(func, s, **kwargs)
  652. def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
  653. """
  654. DRY routine for setting up a GeoQuerySet method that attaches a
  655. Geometry attribute and takes a Geoemtry parameter. This is used
  656. for geometry set-like operations (e.g., intersection, difference,
  657. union, sym_difference).
  658. """
  659. s = {
  660. 'geom_args': ('geom',),
  661. 'select_field': GeomField(),
  662. 'procedure_fmt': '%(geo_col)s,%(geom)s',
  663. 'procedure_args': {'geom': geom},
  664. }
  665. if connections[self.db].ops.oracle:
  666. s['procedure_fmt'] += ',%(tolerance)s'
  667. s['procedure_args']['tolerance'] = tolerance
  668. return self._spatial_attribute(func, s, **kwargs)
  669. def _geocol_select(self, geo_field, field_name):
  670. """
  671. Helper routine for constructing the SQL to select the geographic
  672. column. Takes into account if the geographic field is in a
  673. ForeignKey relation to the current model.
  674. """
  675. opts = self.model._meta
  676. if geo_field not in opts.fields:
  677. # Is this operation going to be on a related geographic field?
  678. # If so, it'll have to be added to the select related information
  679. # (e.g., if 'location__point' was given as the field name).
  680. self.query.add_select_related([field_name])
  681. compiler = self.query.get_compiler(self.db)
  682. compiler.pre_sql_setup()
  683. for (rel_table, rel_col), field in self.query.related_select_cols:
  684. if field == geo_field:
  685. return compiler._field_column(geo_field, rel_table)
  686. raise ValueError("%r not in self.query.related_select_cols" % geo_field)
  687. elif geo_field not in opts.local_fields:
  688. # This geographic field is inherited from another model, so we have to
  689. # use the db table for the _parent_ model instead.
  690. tmp_fld, parent_model, direct, m2m = opts.get_field_by_name(geo_field.name)
  691. return self.query.get_compiler(self.db)._field_column(geo_field, parent_model._meta.db_table)
  692. else:
  693. return self.query.get_compiler(self.db)._field_column(geo_field)
  694. class GeoValuesQuerySet(ValuesQuerySet):
  695. def __init__(self, *args, **kwargs):
  696. super(GeoValuesQuerySet, self).__init__(*args, **kwargs)
  697. # This flag tells `resolve_columns` to run the values through
  698. # `convert_values`. This ensures that Geometry objects instead
  699. # of string values are returned with `values()` or `values_list()`.
  700. self.query.geo_values = True
  701. class GeoValuesListQuerySet(GeoValuesQuerySet, ValuesListQuerySet):
  702. pass