PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/db/models/query.py

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